algorhythm
algorhythm

Reputation: 3426

Removing buttons programmatically

In my code I create buttons programmatically as I do not know how many I need until a file is parsed

buttons= new LinkedList<Button>();
    for(int i=0; i< aList.size();i++)
    {
        Button btn = new Button(this);
        btn.setId(i);
        btn.setOnClickListener(this);
        btn.setText(stringList.get(i));
        btn.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        buttons.add(btn);
        layout.addView(btn);
    }

This works fine, I'm just wondering if there is a quick way to delete all these buttons before creating more (I change the values of the buttons to new ones when the user presses an seperate button)

Upvotes: 1

Views: 7969

Answers (3)

algorhythm
algorhythm

Reputation: 3426

Solved the problem with another for loop

for(int i=0; i< aList.size();i++)
    {
        Button btn;
        btn = buttons.get(i);
        layout.removeView(btn);
    }

Upvotes: 9

Eric Lee
Eric Lee

Reputation: 61

You can do something like this

View v = (View) findViewById(id);
((ViewManager)v.getParent()).removeView(v);

Found here: Add & delete view from Layout

Upvotes: 6

Pierry
Pierry

Reputation: 989

You can set invisible.

myButton.setVisibility(View.INVISIBLE);

Upvotes: 3

Related Questions