【问题标题】:How to disable a RadioGroup until checkbox is checked如何在选中复选框之前禁用 RadioGroup
【发布时间】:2012-03-11 17:28:54
【问题描述】:

我有一个单选组,我不希望用户能够选择任何按钮,直到在我的应用程序中选择了一个特定的复选框。如果未选中该复选框,则会禁用无线电组。我该怎么做。

【问题讨论】:

    标签: android checkbox radio-group


    【解决方案1】:

    Kotlin 解决方案

    for (index in 0..radio.childCount - 1)
        radio.getChildAt(index).isEnabled = false
    

    【讨论】:

      【解决方案2】:

      RadioGroup 不能直接禁用,我们必须循环遍历单选按钮并将启用设置为 false。

      // To disable the Radio Buttons of radio group.
          for (int i = 0; i < radioGroup.getChildCount(); i++) {
              radioUser.getChildAt(i).setEnabled(false);
          }
      

      【讨论】:

      • 如果 for 循环是动态的,“radioUser”变量应该是什么?
      【解决方案3】:

      如果您只有几个单选按钮,更好的方法是为所有孩子设置可点击(假)

      radiobutton1.setClickable(false);
      radiobutton2.setClickable(false);
      radiobutton3.setClickable(false);
      

      【讨论】:

        【解决方案4】:

        真正的诀窍是遍历所有子视图(在本例中:CheckBox)并将其称为 setEnabled(boolean)

        这样的事情应该可以解决问题:

        //initialize the controls
        final RadioGroup rg1 = (RadioGroup)findViewById(R.id.radioGroup1);
        CheckBox ck1 = (CheckBox)findViewById(R.id.checkBox1);
        
        //set setOnCheckedChangeListener()
        ck1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        
            @Override
            public void onCheckedChanged(CompoundButton checkBox, boolean checked) {
                //basically, since we will set enabled state to whatever state the checkbox is
                //therefore, we will only have to setEnabled(checked)
                for(int i = 0; i < rg1.getChildCount(); i++){
                    ((RadioButton)rg1.getChildAt(i)).setEnabled(checked);
                }
            }
        });
        
        //set default to false
        for(int i = 0; i < rg1.getChildCount(); i++){
            ((RadioButton)rg1.getChildAt(i)).setEnabled(false);
        }
        

        【讨论】:

        • 很高兴知道我所做的“肮脏黑客”似乎是这样做的实际方式。 :D
        【解决方案5】:

        根据复选框的状态采取行动,并相应地设置无线电组。 假设您有一个名为 radiogroup 的无线电组,您可以通过

        启用或禁用无线电组

        radiogroup.setEnabled(true);

        将 OnCheckedChangeListener() 添加到您的复选框。

        【讨论】:

        • 必须禁用单个 RadioButton 项。
        【解决方案6】:

        您可以在 CheckBox 上使用 onCheckedChangeListener 并在 RadioGroup 上使用方法 setEnabled

        最好的祝愿, 蒂姆

        【讨论】:

        • 抱歉,这不适用于 RadioGroup。它似乎不会向下传播。
        猜你喜欢
        • 2015-02-20
        • 2015-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-04
        • 2013-01-19
        • 2014-07-11
        相关资源
        最近更新 更多