Get the array of RadioButtons in a RadioGroup in Android

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-26 20:33:58

问题


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.


回答1:


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");



回答2:


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.



来源:https://stackoverflow.com/questions/5096329/get-the-array-of-radiobuttons-in-a-radiogroup-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!