How to disable a RadioGroup until checkbox is checked

W0lf7 picture W0lf7 · Feb 21, 2012 · Viewed 37.9k times · Source

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.

Answer

ariefbayu picture ariefbayu · Feb 21, 2012

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