androidandroid-checkboxoncheckedchanged

How to disable checkbox when a limit is reached in android?


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?


Solution

  • you should use a other variable for counting number of checkboxs that checked

    final int count=0; 
    OnCheckedChangeListener checker = new OnCheckedChangeListener(){ 
            @Override
            public void onCheckedChanged(CompoundButton cb, boolean b) {
               if(count == maxLimit && b){
                   cb.setChecked(false);
                   Toast.makeText(getApplicationContext(), 
                "Limit reached!!!", Toast.LENGTH_SHORT).show();
               }else if(b){
    
                    count++;
                    CharSequence myCheck = tagsCheck[i].getText();
                    Toast.makeText(getApplicationContext(), 
                           myCheck + " checked!", 
                           Toast.LENGTH_SHORT)
                    .show();
                }else if(!b){
     count--;
            }
        };