【问题标题】:Get the array of RadioButtons in a RadioGroup in Android获取 Android 中 RadioGroup 中的 RadioButtons 数组
【发布时间】:2011-07-03 01:14:46
【问题描述】:

有没有办法在 Android RadioGroup 中获取 RadioButtons 的数组(或集合)?我想将单个侦听器添加到单选按钮,但我没有看到任何明显的迭代它们的方法。

【问题讨论】:

    标签: android arrays radio-button iteration radio-group


    【解决方案1】:

    这应该可以解决问题:

            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】:

    为什么需要查询radioGroup?为什么你不能直接在 RadioButton 上设置你的监听器,你必须能够持有 radioButtons,因为你是把它们添加到 RadioGroup 的人。

    无论如何,RadioGroup 只是一种特殊类型的 LinearLayout,它的所有子元素都是您添加的 RadioButton。您可以遍历所有子视图以访问 RadioButtons。

    【讨论】:

    • 我在 XML 布局中创建了 RadioGroup,所以所有 RadioButton 已经是其中的一部分。我从来没有在代码中手动添加它们。感谢您的回答
    猜你喜欢
    • 2012-06-10
    • 2012-05-05
    • 2018-04-17
    • 2014-04-01
    • 1970-01-01
    • 2014-03-10
    • 2012-08-29
    • 1970-01-01
    • 2013-07-15
    相关资源
    最近更新 更多