Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove radio button items programmatically

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.

like image 780
Radiak Avatar asked Sep 22 '12 20:09

Radiak


2 Answers

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 :)

like image 99
M090009 Avatar answered Nov 18 '22 10:11

M090009


My first guess is that this portion of code is bad:

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

you can't run over one view's children while removing child at the same time (rg.getChildCount() will change during the run)

like image 4
dor506 Avatar answered Nov 18 '22 09:11

dor506