Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set selected index of an Android RadioGroup

Is there a way to set the selected index of a RadioGroup in android, other than looping through the child radiobuttons and selecting checking the radio button at the selected index?

Note: I am populating the Radio Button Group at run time.

like image 359
Hassan Mokdad Avatar asked Mar 23 '12 16:03

Hassan Mokdad


2 Answers

If your radio group is defined in a layout xml file, each button can be assigned an id. Then you just check a button like this

radioGroup.check(R.id.myButtonId); 

If you created your radio group programmatically (I'm not even sure how you do this...), you might want to consider creating a special layout xml file just for the radio group so that you can assign R.id.* ids to the buttons.

Please see the answer below if you are, in fact, looking to set the radio button group by index, see the answer below.

((RadioButton)radioGroup.getChildAt(index)).setChecked(true); 
like image 79
jjm Avatar answered Sep 18 '22 17:09

jjm


Question said "set selected INDEX", here's how to set it by index:

((RadioButton)radioGroup.getChildAt(index)).setChecked(true); 

........

Additional info: It seems that Google wants you to use id instead of index, because using id is more bug proof. For example, if you have another UI element in your RadioGroup, or if another developer re-orders the RadioButtons, the indices might change and not be what you expected. But if you're the only developer, this is totally fine.

like image 24
Siavash Avatar answered Sep 19 '22 17:09

Siavash