Android Checkable Menu Item Android Checkable Menu Item android android

Android Checkable Menu Item


Layout looks right. But you must check and uncheck menu item in code.

From the documentation:

When a checkable item is selected, the system calls your respective item-selected callback method (such as onOptionsItemSelected()). It is here that you must set the state of the checkbox, because a checkbox or radio button does not change its state automatically. You can query the current state of the item (as it was before the user selected it) with isChecked() and then set the checked state with setChecked().


Wrap the items in a group element, like this:

<menu xmlns:android="http://schemas.android.com/apk/res/android">    <group android:checkableBehavior="all">        <item android:id="@+id/item1"              android:titleCondensed="Options"              android:title="Highlight Options"              android:icon="@android:drawable/ic_menu_preferences">        </item>        <item android:id="@+id/item2"              android:titleCondensed="Persist"              android:title="Persist"              android:icon="@android:drawable/ic_menu_preferences"              android:checkable="true">        </item>    </group></menu>

From the Android docs:

The android:checkableBehavior attribute accepts either:

single - Only one item from the group can be checked (radio buttons)

all - All items can be checked (checkboxes)

none - No items are checkable


You can create a checkable menu item by setting the actionViewClass to a checkable widget like android.widget.CheckBox

res/menu/menu_with_checkable_menu_item.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto">    <item        android:id="@+id/action_favorite"        android:checkable="true"        android:title="@string/action_favorite"        app:actionViewClass="android.widget.CheckBox"        app:showAsAction="ifRoom|withText" /></menu>

And you can can even style it to be a checkable star if you set actionLayout to a layout with a styled android.widget.CheckBox

res/layout/action_layout_styled_checkbox.xml

<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"    style="?android:attr/starStyle"    android:layout_width="wrap_content"    android:layout_height="wrap_content" />

res/menu/menu_with_checkable_star_menu_item.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto">    <item        android:id="@+id/action_favorites"        android:checkable="true"        android:title="@string/action_favorites"        app:actionLayout="@layout/action_layout_styled_checkbox"        app:showAsAction="ifRoom|withText" /></menu>

To set the value

menuItem.setChecked(true/false);

To get the value

menuItem.isChecked()

Cast MenuItem to CheckBox

CheckBox checkBox= (CheckBox) menuItem.getActionView();