Android - keep options menu open

2019-02-17 04:24发布

I have an Options menu up and running in my Android application and I've overridden the onCreateOptionsMenu, onOptionsItemSelected and onPrepareOptionsMenu methods to customize the menu a little.

My question is related to keeping the Options menu open after the user clicks on a menu item. Basically, I'd like to be able to hide the menu until the user clicks on the device menu key. Once the user clicks on this key, I'd like to be able to hold the menu in place regardless of how many times the user clicks on menu items. If the user wants to hide the Options menu, they'd just need to click on the device menu key again.

Is this type of interaction supported (or even advisable). If this interaction is not supported, any alternative suggestions are more than welcome.

Cheers!

Sean

标签: android menu
2条回答
Explosion°爆炸
2楼-- · 2019-02-17 05:06

This will not be possible with onCreateOptionsMenu and the other methods. They always act that way.

But you can do it another way. But there you have to program the whole menu yourself. Basically add the Menu in your layout.xml and let it be hidden (visibility = gone). Then you overwrite the methods onKeyDown. There you check if it is the Menu key. if the menu is not yet open yes, then you show the menu. If it is open already, you hide it.

should not be too difficult. Good thing as well is, that you can make the menu look exactly the way you want and as well let it react the way you want.

查看更多
手持菜刀,她持情操
3楼-- · 2019-02-17 05:24

For anybody like me, who found this question in google:

To keep menu open after selecting item, you need this code:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    item.setChecked(!item.isChecked());

    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;
}

Important to return false in onOptionsItemSelected and methods of OnActionExpandListener

This solution from @MayurGajra. More details here: How to hold the overflow menu after I click it?

查看更多
登录 后发表回答