How to detect when user presses “menu” key on thei

2020-07-17 05:34发布

问题:

I know I can override onBackPressed() on higher API levels to detect if the back key is pressed. Is there a similar way to do it for the menu button? I'm not a big fan of checking keycode in KeyEvents. Thanks!

回答1:

If you are just looking to create a key listener for the menu button you should be overriding onKeyDown and checking the keycode. Now since you pointed out that you are not a big fan of that you could also override onPrepareOptionsMenu which is called everytime the menu button is clicked and a menu is shown to the user. I am not sure if this is called if you have not supplied a menu inside the onCreateOptionsMenu method.



回答2:

Are you in search of this????:

public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            //do your work
            return true;
        }
        return super.onKeyDown(keyCode, event); 
    }