java - How to limit number of checkboxes that can be checked? -
i have 4 checkboxes. want user select 2 of them. how set limit?
you can have int
variable stores how many checkboxes checked... time oncheckedchanged()
called, check variable , if third checkbox checked, set unchecked again...
let's start checkboxes unchecked. do:
int numberofcheckboxeschecked = 0;
then set oncheckchangedlistener
:
checkbox1.setoncheckedchangelistener(new oncheckedchangelistener() { @override public void oncheckedchanged(compoundbutton buttonview, boolean ischecked) { if (ischecked && numberofcheckboxeschecked >= 2) { checkbox1.setchecked(false); } else { // checkbox either got unchecked // or there less 2 other checkboxes checked // change counter accordingly if (ischecked) { numberofcheckboxeschecked++; } else { numberofcheckboxeschecked--; } // fine , can whatever // checking checkbox should here } } });
(i have not tested code, should work.)