Checkboxes let the user select one or more options from a set. Typically, you present checkbox options in a vertical list.
To create each checkbox option, create a
CheckBox
in your layout. Because
a set of checkbox options lets the user select multiple items, each checkbox is managed separately,
and you must register a click listener for each one.
Respond to click events
Begin by creating a layout with CheckBox
objects in a list:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <CheckBox android:id="@+id/checkbox_meat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Meat" /> <CheckBox android:id="@+id/checkbox_cheese" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cheese"/> </LinearLayout>
Once your layout is ready, head to your Activity
or Fragment
, find your
CheckBox
views, and set a change listener, as in the following example:
Kotlin
findViewById<CheckBox>(R.id.checkbox_meat) .setOnCheckedChangeListener { buttonView, isChecked -> Log.d("CHECKBOXES", "Meat is checked: $isChecked") } findViewById<CheckBox>(R.id.checkbox_cheese) .setOnCheckedChangeListener { buttonView, isChecked -> Log.d("CHECKBOXES", "Cheese is checked: $isChecked") }
Java
findViewById<CheckBox>(R.id.checkbox_meat) .setOnCheckedChangeListener { buttonView, isChecked -> Log.d("CHECKBOXES", "Meat is checked: $isChecked"); } findViewById<CheckBox>(R.id.checkbox_cheese) .setOnCheckedChangeListener { buttonView, isChecked -> Log.d("CHECKBOXES", "Cheese is checked: $isChecked"); }
The previous code prints a message in Logcat every time the checkboxes change status.