You can easily have an int
variable that stores how many checkboxes are currently checked... Then any time onCheckedChanged()
is called, you check that variable and if it would already be a third checkbox to be checked, you just set it to unchecked again...
Let's say you start with all the checkboxes unchecked. So you do:
int numberOfCheckboxesChecked = 0;
Then you set the OnCheckChangedListener
:
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked && numberOfCheckboxesChecked >= 2) {
checkbox1.setChecked(false);
} else {
// the checkbox either got unchecked
// or there are less than 2 other checkboxes checked
// change your counter accordingly
if (isChecked) {
numberOfCheckboxesChecked++;
} else {
numberOfCheckboxesChecked--;
}
// now everything is fine and you can do whatever
// checking the checkbox should do here
}
}
});
(I have not tested the code, but it should work.)