Toolbar : overflow menu button always showing

霸气de小男生 提交于 2019-12-03 08:56:45

I found the solution to my problem:

1- don't call setSupportActionBar(mToolbar); any more, instead use Toolbar directly

2- check if device has a hardware menu button by calling ViewConfigurationCompat.hasPermanentMenuKey(ViewConfiguration.get(getApplicationContext())); :

3- if device has menu button i return true on in onCreateOptionsMenu, else i inflate the menu in the Toolbar

You can change the behavior of the hardware menu button when it is present to show/hide the toolbar overflow menu. To do so, override the onKeyUp method of Activity.

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        if (mToolbar.isOverflowMenuShowing()) {
            mToolbar.hideOverflowMenu();
        } else {
            mToolbar.showOverflowMenu();
        }
        return true;
    }
    return super.onKeyUp(keyCode, event);
}

It works fine (at least for me).

In the onCreate method of your activity do:

    boolean hasHarwareMenu = ViewConfigurationCompat.hasPermanentMenuKey(ViewConfiguration.get(getApplicationContext()));
    if (!hasHarwareMenu) setSupportActionBar(toolbar);

And inflate your menu.xml as normal in the onCreateOptionsMenu.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!