lundi 8 mai 2017

Setting OnClickListener for array of checkboxes

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




Aucun commentaire:

Enregistrer un commentaire