how to remove radio button items programmatically
Solution 1
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)
Solution 2
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 :)
Radiak
Updated on June 24, 2022Comments
-
Radiak almost 2 years
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.