0

I have an array of checkboxes that all need an OnClickListener to see when they're checked/unchecked. Here's what I have:

CheckBox[] sens = new CheckBox[3];
for (int i = 0; i < 3; i++)
{
    cb = new CheckBox(this);
    cb.setText(strings[i]);
    cb.setOnClickListener(new View.OnClickListener() {
                              @Override
                              public void onClick(View v) {
                                  if (cb.isChecked()) {
                                      System.out.println("Checked");
                                  } else {
                                      System.out.println("Unchecked");
                                  }
                              }
                          });
    sens[i] = cb;
    mainlayout.addView(sens[i]);
}

But the monitor/console only prints "Unchecked", no matter if it's checked or not. Is there a better method to do this? The checkboxes need to be dynamic

1 Answer 1

1

You should use the setOnCheckedChangeListener method instead of setOnClickListener, and you can use the setTag method to set a position/id to handle the checkboxes.

Documentation: Register a callback to be invoked when the checked state of this button changes.

private void createCheckBoxes(final int count) {
    for (int i = 0;i < count; i++) {
        final CheckBox checkBox = createCheckBox(this, strings[i], i);
        mainlayout.addView(checkBox);
    }
}

private CheckBox createCheckBox(final Context context, final String text, final int id) {
    final CheckBox checkBox = new CheckBox(context);

    checkBox.setTag(id);
    checkBox.setText(text);
    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            if (isChecked) {
                System.out.println("Checked");
            } else {
                System.out.println("Unchecked");
            }
        }
    });

    return checkBox;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.