CheckBox checkBox = new CheckBox(context); checkBox.setText("Check me!"); checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // perform action when checkbox is selected } else { // perform action when checkbox is unselected } } });
ListView listView = new ListView(context); ArrayAdapterBoth examples use the "CompoundButton.OnCheckedChangeListener" interface to handle the selection state change of the checkboxes. The package that contains the CheckBox class and other Android user-interface components is "android.widget".adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_multiple_choice, choices); listView.setAdapter(adapter); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { SparseBooleanArray checkedItems = listView.getCheckedItemPositions(); for (int i = 0; i < checkedItems.size(); i++) { int index = checkedItems.keyAt(i); if (checkedItems.get(index)) { // perform action when checkbox at position index is selected } else { // perform action when checkbox at position index is unselected } } } });