androidcheckboxandroid-checkbox

Selecting one Checkbox out of multiple checkboxes & getting user selected Checkbox



I have 16 checkboxes in an activity out of which user has to select any 1 out of 8 checkboxes.
So, ultimately user will be selecting 2 checkboxes out of 16 of them.

Update:The checkboxes are already there in the xml layout file. So, I do have access to their ID's

Till now, I was thinking to implement a simple onCheckedChange listener and in a switch case block select any 1 checkbox out of 8 checkboxes and deselect the rest 7 of them. But this approach is extremely painful.

Also, when I would need to extract which of them is selected then it would be a complete mess.

So, what is the simplest yet flexible way I can do both of these things? Suggestions are welcome
Thanks


Solution

  • You can keep only one CheckBox checked at a time(similar to a RadioGroup) by grouping them in an array(for easy access and handling) and also setting a OnClickListener to each one to set the status:

    CheckBox[] chkArray = new CheckBox[8];
    chkArray[0] = (CheckBox) findViewById(R.id.cb1R1);
    chkArray[0].setOnClickListener(mListener);
    chkArray[1] = (CheckBox) findViewById(R.id.cb2R1); // what id do you have?
    chkArray[1].setOnClickListener(mListener);
    // so on for the rest of the 8 CheckBoxes
    
    private OnClickListener mListener = new OnClickListener() { 
    
         @Override
         public void onClick(View v) {
            final int checkedId = v.getId();
            for (int i = 0; i < chkArray.length; i++) {
                final CheckBox current = chkArray[i];
                if (current.getId() == checkedId) {
                     current.setChecked(true);
                } else {
                     current.setChecked(false);
                }
           }    
        }
    };