How To Limit Number Of Checkboxes That Can Be Checked?
I have 4 checkboxes. I want user to select only two of them. How to set that limit?
Solution 1:
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(newOnCheckedChangeListener() {
@OverridepublicvoidonCheckedChanged(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 accordinglyif (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.)
Post a Comment for "How To Limit Number Of Checkboxes That Can Be Checked?"