Is there any way of getting an array (or a collection) of the RadioButton
s in an Android RadioGroup
? I would like to add individual listeners to radio buttons but I don't see any obvious way of iterating over them.
Asked
Active
Viewed 2.6k times
33

Tim
- 5,767
- 9
- 45
- 60
3 Answers
64
this should do the trick:
int count = radioGroup.getChildCount();
ArrayList<RadioButton> listOfRadioButtons = new ArrayList<RadioButton>();
for (int i=0;i<count;i++) {
View o = radioGroup.getChildAt(i);
if (o instanceof RadioButton) {
listOfRadioButtons.add((RadioButton)o);
}
}
Log.d(TAG,"you have "+listOfRadioButtons.size()+" radio buttons");

zrgiu
- 6,200
- 1
- 33
- 35
-
hey i too have created an array of radio buttons but i want to uncheck all and then check only one out of that arraylist ..how can i do it ?? – Shruti Mar 11 '13 at 09:41
1
Why do you need to query the radioGroup? Why cant you directly set your listeners on the RadioButton, you must be able to get a hold of the radioButtons since you are the one who is adding them to the RadioGroup.
Regardless, RadioGroup is simply a special type of LinearLayout, all its children are RadioButtons that you have added. You can loop through all the child views to access the RadioButtons.

Veeresh
- 1,052
- 7
- 12
-
I created the `RadioGroup` in XML layout so all the `RadioButton`'s were part of that already. I never manually added them in code. Thanks for your answer – Tim Feb 23 '11 at 21:01
0
Working example for RadioGroup with five RadioButtons (Kotlin):
private fun initUIListeners() {
with(binding) {
rb1.setOnClickListener(rbClick(radioGroup))
rb2.setOnClickListener(rbClick(radioGroup))
rb3.setOnClickListener(rbClick(radioGroup))
rb4.setOnClickListener(rbClick(radioGroup))
rb5.setOnClickListener(rbClick(radioGroup))
}
}
private fun rbClick(radioGroup: RadioGroup): (View) -> Unit = {
val radioButton = it as MaterialRadioButton
when {
!radioButton.isSelected -> {
radioButton.isChecked = true
radioButton.isSelected = true
unselectExcept(radioButton, radioGroup)
}
else -> {
radioButton.isChecked = false
radioButton.isSelected = false
radioGroup.clearCheck()
}
}
}
private fun unselectExcept(
radioButton: MaterialRadioButton,
radioGroup: RadioGroup,
) = (0 until radioGroup.childCount)
.map { radioGroup.getChildAt(it) }
.filterIsInstance<MaterialRadioButton>()
.filter { it != radioButton }
.forEach { it.isSelected = false }

Smirnov Sergey
- 409
- 1
- 8
- 12