how to remove radio button items programmatically
Asked Answered
A

2

5

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.

Ander answered 22/9, 2012 at 20:14 Comment(0)
P
4

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)

Phytohormone answered 22/9, 2012 at 20:25 Comment(0)
O
31

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

Odalisque answered 15/3, 2013 at 18:28 Comment(0)
P
4

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)

Phytohormone answered 22/9, 2012 at 20:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.