Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding the physical menu button on android

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?

like image 576
Arielle Avatar asked Oct 05 '13 20:10

Arielle


2 Answers

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.

like image 131
free3dom Avatar answered Oct 26 '22 23:10

free3dom


I use this in my activity to override the Back key, it should work the same for the Menu key:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
  if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
    // Show your menu
  } else {
    return super.onKeyDown(keyCode, event);
  }
}
like image 39
DevOfZot Avatar answered Oct 27 '22 00:10

DevOfZot