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
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);
}
}
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.