I have 15 CheckBox
and I must to stuck user when he checks more than 5. I use the method OnCheckedChangeListener
to know if an item is checked, but I don't know how to limit after 5 items selected.
See my code below:
int lengthBox = 15;
int lenghtCount = 0;
// inside onCreate method
final CheckBox[] checkbox = new CheckBox[lengthBox];
OnCheckedChangeListener checker = new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton cb, boolean b) {
// How can I improve this condition?
if(checkbox[0].isChecked() || checkbox[1].isChecked() ||
checkbox[2].isChecked() || checkbox[3].isChecked() ||
checkbox[4].isChecked() || checkbox[5].isChecked() ||
checkbox[6].isChecked() || checkbox[7].isChecked() ||
checkbox[8].isChecked() || checkbox[9].isChecked() ||
checkbox[10].isChecked() || checkbox[11].isChecked() ||
checkbox[12].isChecked() || checkbox[13].isChecked() ||
checkbox[14].isChecked()) {
if(lenghtCount < 5){
lenghtCount++;
}else{
Toast.makeText(MyActivity.this, "Limit reached!!!", Toast.LENGTH_SHORT).show();
}
}
}
};
for(int i = 0; i < lengthBox; i++) {
int id = getResources().getIdentifier("checkbox_"+i, "id", getPackageName());
checkbox[i] = (CheckBox) findViewById(id)
checkbox[i].setOnCheckedChangeListener(checker);
}
Can someone point me in the right way, please?
UPDATE: I tried:
OnCheckedChangeListener checker = new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton cb, boolean b) {
if(lenghtCount == 5){
cb.setChecked(false);
}else if(b){
lenghtCount++;
}else if(!b){
lenghtCount--;
}
}
};
Works perfectly but I think something is missing. When I click 5 items this works, but after when I unselect them, I can't recheck any item. What I'm missing?
I am not sure but something like this might help you. create a global count variable and every time a checkbox is checked, increase count by 1 and once count reaches max, disable further checks. Do something like this :
Try this.. Create
int check = 0;
as globalyou should use a other variable for counting number of checkboxs that checked
Suppose You Have To Select Maximum 2 CheckBoxes Out OF 4 Then Following Code Is Useful:-
);
Do Same for Another 3 Checkbox You Can Also Do This By Using Checkchanged Listener To Whole Array(CBA[i].setOnCheckedChangeListener)............Hope It Will Be Useful