Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the array of RadioButtons in a RadioGroup in Android

Is there any way of getting an array (or a collection) of the RadioButtons 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.

like image 322
Tim Avatar asked Feb 23 '11 19:02

Tim


2 Answers

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");
like image 153
zrgiu Avatar answered Nov 05 '22 15:11

zrgiu


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.

like image 1
Veeresh Avatar answered Nov 05 '22 14:11

Veeresh