supera supera - 3 years ago 121
Android Question

Dynamically add or remove views

For my project I need a functionality to dynamically add and remove views(textedit or buttons, etc).

I saw this similar functionality in Android "Add Contact" screen, where plus button add new fields and minus button delete the fields.

I found that
is the file behind "Add Contacts".

I tried to find the methods that are called when plus or minus buttons are pressed but unable to find it, seems like "Add Contact" code is spreaded over multiple files. I am having difficulty understanding Android source code because documentation is unavailable.

Any advice?

Answer Source

You can add and remove views by calling .add() or .remove() on the reference to your main layout and passing the view you wish to add or remove;

Here is a simple example of an onCreate method that demonstrates adding and removing a button:

public void onCreate(Bundle savedInstanceState) {

    LinearLayout myMainLayout = (LinearLayout)findViewById(;
    Button b = new Button(this);
    //you can have some b.setXXX calls here to set text, view, click listeners etc...

    //to remove

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download