This is how i did it.
Add following code in your activity where option menu is implemented.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//your checking other stuff
item.setChecked(!item.isChecked());
//main part for holding onto the menu
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
item.setActionView(new View(this));
item.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return false;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return false;
}
});
return false;
}
By adding the line: item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
I am marking the item as it has expandable/collapsible behavior so it will call the setOnActionExpandListener
.
This line here: item.setActionView(new View(this));
is a view when item is in expanded state.It is just a dummy view because we will never let it expand how i am going to explain next.
You see that i am returning false from both the methods of setOnActionExpandListener
to suppress expansion and collapsing of the item so the view we gave in previous step would never show up and menu would remain open.
Following would be your menu file:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<group android:checkableBehavior="all">
<item
android:id="@+id/action_check"
android:orderInCategory="1"
android:title="Title 1"
app:showAsAction="never" />
<item
android:id="@+id/notification"
android:orderInCategory="2"
android:title="Title 2"
app:showAsAction="never" />
<item
android:id="@+id/about"
android:orderInCategory="3"
android:title="Title 3"
app:showAsAction="never" />
</group>
</menu>
Notice the line group android:checkableBehavior="all"
is to tell that all items in the group will have checkable behavior so that you don't have to write checkable in each item.