Add checkboxes to your app

Try the Compose way
Jetpack Compose is the recommended UI toolkit for Android. Learn how to add components in Compose.

Checkboxes let the user select one or more options from a set. Typically, you present checkbox options in a vertical list.

Figure 1. An example of checkboxes from Material Design Checkbox.

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:

<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBoxandroid:id="@+id/checkbox_meat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Meat"/>
<CheckBoxandroid: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.

Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Last updated 2024年10月31日 UTC.