edi233
edi233

Reputation: 3031

Listener for check boxes in android

I have a layout with 10 check boxes. All check boxes are added through code. Now I was wondering if there's any listener available for the layout to check how many check boxes are selected. For instance: when I select 4 check boxes, I want to know how many and which check boxes were selected.

Upvotes: 0

Views: 80

Answers (2)

chaitanya
chaitanya

Reputation: 1756

you can add checkbox like CheckBox cb = new CheckBox(this); cb.setText("Dynamic Checkbox " + i); cb.setId(i+10); yourlayout.addView(cb); you have to jst set their listener by calling setOnClickListerner(this); here. It will solve your issue.

Upvotes: 0

g00dy
g00dy

Reputation: 6778

Try this, taken from here:

ckBox.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {

      if (ckBox.isChecked()) {
        mDisplayHelp = true;
      } else {
        mDisplayHelp = false;
      }
      SharedPreferences.Editor editor = prefs.edit();
      editor.putBoolean("checkboxPref", mDisplayHelp);

      // Don't forget to commit your edits!!!
      editor.commit();
      // Optional part
    }
});

Or you can just check each one of them like that:

checkBox = (CheckBox) findViewById(R.id.chkbox);
if (checkBox.isChecked()) {
    // Some wild things happen here
} else {
    // Okay ...
}

Upvotes: 1

Related Questions