Overriding the physical menu button on android

后端 未结 2 1719
小蘑菇
小蘑菇 2021-01-05 07:31

I would like the menu key on my Android device to open a dialog instead of opening the menu while my app is running. I tried to code that into onCreateOptionsMenu(Menu

2条回答
  •  有刺的猬
    2021-01-05 08:12

    You can override the default behavior of system key presses by intercepting them in your Activity. This is done by overriding the onKeyDown event, and returning true if you want to prevent the key from being handled by the system. The code for your case should look something as follows:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
       if ( keyCode == KeyEvent.KEYCODE_MENU ) {
    
           // perform your desired action here
    
           // return 'true' to prevent further propagation of the key event
           return true;
       }
    
       // let the system handle all other key events
       return super.onKeyDown(keyCode, event);
    }
    

    This may not work for all keys though; the reason for this is that keys are sent to the current view before the activity receives this message. In this case you will need to override the onKeyDown for the current view as well.

提交回复
热议问题