2012-02-21 89 views
21

我有我不想用户,直到一个特定的复选框我的应用程序中选择可以选择任何按钮的单选按钮组禁用RadioGroup中。如果该复选框取消选中是那么这将禁用无线电组。我该如何去做这件事。如何,直到复选框被选中

回答

51

真正的窍门是遍历所有儿童观看(在这种情况下: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); 
} 
+0

很高兴知道我所做的“肮脏的黑客攻击”似乎是实际的做法。 :d – WORMSS 2013-07-11 08:00:36

0

您可以使用您的CheckBox的onCheckedChangeListener和使用方法setEnabled您RadioGroup中。

最良好的祝愿, 添

+4

radiogroup.setEnabled(真);不起作用 – Elchin 2012-08-08 10:30:03

+3

对不起,但这对RadioGroup无效。它似乎并没有传播下去。 – WORMSS 2013-04-21 21:28:50

-1

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

启用或禁用该radiogroup radiogroup.setEnabled(true);

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

+4

radiogroup.setEnabled(true);不起作用 – Elchin 2012-08-08 10:29:28

+2

必须禁用单个RadioButton项目。 – 2015-11-01 16:41:10

0

RadioGroup中不能直接禁止,我们通过单选按钮必须循环,并将其设置为启用假。