Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle check and uncheck dynamically created checkbox in android

i have created check boxes using loop and i want to validate it. Like i just want to check only 3 from the check boxes , when i press on the 4th one it should show an alert and uncheck it.

enter image description here

And i am able to get the alert when i press the 4the one but it is not unchecking.

anybody faced such issue and how did you solve it ?

like image 232
Kris Avatar asked Sep 21 '12 17:09

Kris


1 Answers

int i;
for (i = 0; i < 20; i++) {
    CheckBox ch = new CheckBox(this);
    ch.setTag(Integer.valueOf(i));
    ch.setText("CheckBox " + i);
    ch.setChecked(false);
    ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                numChecked++;
            } else {
                numChecked--;
            }

            if (numChecked == 4) {
                buttonView.setChecked(false);
                numChecked--;
                // fourth one selected, show your dialog
            }
        }
    });
}

You will also need a global variable call numChecked:

int numChecked = 0;

You will also need to add a .addView(ch) in the loop's end to add the CheckBoxes to your layout.

like image 142
Raghav Sood Avatar answered Oct 10 '22 04:10

Raghav Sood