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.

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 ?

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.


Need Your Help

precision or recall speaks loud?

machine-learning precision classification document-classification recall

Say I'm evaluating some text classification research project using two approaches 'A' and 'B'. When using approach 'A', I get a x% increase in precision while with 'B', a x% increase in recall. How...

Multiple colors in a UITableViewCell

iphone ios uitableview ios5

Given the following UITableViewCell code, how can we make myObj.firstName red and myObj.lastName green?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.