Overriding the physical menu button on android

Arielle picture Arielle · Oct 5, 2013 · Viewed 7.3k times · Source

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 menu) but it worked only for the first time I pressed the menu button. Can I do it in some other way?

Answer

free3dom picture free3dom · Oct 7, 2013

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.