Android Check box Group

Mohamed Sobhy picture Mohamed Sobhy · Apr 12, 2012 · Viewed 52.4k times · Source

I'm trying to apply some kind of validation on a group of check boxes (e.g. Two contradictory items cannot be checked together) so I want to somehow group Check Box objects and apply something like RequiredFieldValidator on the whole group once and in that validator I will register listeners and do the whole check on my Check Boxes objects.

What I imagine would be a code that look like that:

CheckBoxView allMyCheckBoxes = new CheckBoxView(checkbox1,checkbox2,checkbox3); //varargs
validate(allMyCheckBoxes);

Validate will contain the logic of contradictory check boxes and everything.

Is that already implemented somewhere in Android? If not, anybody tried out something like that? (Hopefully share it with us here)

Answer

user665270 picture user665270 · Dec 19, 2012

This logic will allow to select one and more checkbox

 private Checkbox day = (checkbox)findviewbyid(R.id.day);
 private Checkbox night =(checkbox)findviewbyid(R.id.night);

 day.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (!night.isChecked() && !day.isChecked()) {
            night.setChecked(true);
        }

    }
});
night.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (!day.isChecked() && !night.isChecked()) {
            day.setChecked(true);
        }

    }
});