How to prevent menu from disappearing on item click in Android?

Viewed 1189

I have a menu in which all items have a checkbox. So it is like a multichoice menu. I don't want the menu to close when an item is clicked. I only want to close the menu on back press. But I can't figure out how to do it?

This is the code:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when(item.itemId) {
        R.id.my_item -> {
            // toggle    
        }
    }

    // something to do here?
    // changing return value to true or false doesn't help
    return false
}
2 Answers

That implementation is hidden under native Android menu management and you get only callback of selected menu item. It would be better to move all choose items to AlertDialog (There is simple example I have just googled and have only one menu item which starts showing that AlertDialog

You'll have to wrap your menu items inside group tag. Refer code below :

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

Follow link to know more about checkable menu items

Related