Reputation: 921
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.
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 ?
Upvotes: 5
Views: 7073
Reputation: 82543
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.
Upvotes: 11