How to disable a RadioGroup until checkbox is checked

丶灬走出姿态 提交于 2019-11-27 04:27:28

问题


I have a radio group which I do not want to user to be able to select any of the buttons until a particular checkbox is selected within my app. If the checkbox is unticked then this disables the radio-group. How do I go about doing this.


回答1:


The real trick is to loop through all children view (in this case: CheckBox) and call it's setEnabled(boolean)

Something like this should do the trick:

//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);
}



回答2:


You can use the onCheckedChangeListener on your CheckBox and use the method setEnabled on your RadioGroup.

Best wishes, Tim




回答3:


If you have just a few radio buttons, better way would be to setClickable(false) for all children

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



回答4:


RadioGroup cannot be disabled directly, we have to loop through the radio button and set it enabled as false.




回答5:


Take actions according to the state of the checkbox and set the radiogroup accordingly. Assuming that you have a radio-group named radiogroup you can enable or disable the radiogroup by

radiogroup.setEnabled(true);

Add a OnCheckedChangeListener() to your checkbox.



来源:https://stackoverflow.com/questions/9376966/how-to-disable-a-radiogroup-until-checkbox-is-checked

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