简体   繁体   中英

Make custom ActionBar More item open when Menu key pressed

As Android doesn't support icons in context menus, I decided to replace the native ActionBar More menu item with my own custom item. The problem is that it doesn't listen for the Menu hardware key presses. Is there any way I can implement this behavior? Actually the problem is to find a way to activate an item in ActionBar by pressing a key. Thanks in advance.

To display your menu (which is an ActionBar item as well) on a hardware menu button click, you can do this (you need to keep a reference to your Menu in the OnCreateOptionsMenu callback):

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(event.getAction() == KeyEvent.ACTION_DOWN){
        switch(keyCode) {
        case KeyEvent.KEYCODE_MENU:
            mainMenu.performIdentifierAction(R.id.your_custom_menu, 0);
           return true;  
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM