how to remove radio button items programmatically

Radiak picture Radiak · Sep 22, 2012 · Viewed 9k times · Source

In xml layout I have RadioGroup, Button1, Button2. When user clicks on button1, several radio buttons are programmatically created in RadioGroup (total amount of radio buttons may differ (pocet = count of radio buttons to be created).

    final RadioButton[] rb = new RadioButton[pocet];        
    RadioGroup rg = (RadioGroup) findViewById(R.id.MyRadioGroup);

    radiobuttonCount++;
    for(int i=0; i<pocet; i++){
        rb[i]  = new RadioButton(this);
        rb[i].setText("Radio Button " + radiobuttonCount);
        rb[i].setId(radiobuttonCount+i);            
        rb[i].setBackgroundResource(R.drawable.button_green);            
        rg.addView(rb[i]);            
    }

What I try to do is this: When user selects xy item from RadioGroup, I'll pass selected value to textview and remove all radioButtons.

For deleting purpose I use:

        public void onCheckedChanged(RadioGroup rGroup, int checkedId)
        {
            RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(checkedId);
            boolean isChecked = checkedRadioButton.isChecked();
            if (isChecked)
            {
                RadioGroup rg = (RadioGroup)    findViewById(R.id.MyRadioGroup);                                        

                for (int i=0; i< rg.getChildCount(); i++){
                    rg.removeViewAt(i);
                }
            }

Problem is that this sometimes works well, but sometimes first radio button remains undeleted.

P.S. Later I want to add button2 that will feed radiogroup with different items and different radio buttons amount. That's why I need to remove all radio buttons after user does selection.

Answer

M090009 picture M090009 · Mar 15, 2013

Its really easy, you just do this:

rg.removeAllViews();

because i worked with the for loop but it didn't remove all the RadioButtons. have fun :)