Overriding the physical menu button on android

混江龙づ霸主 提交于 2020-03-14 07:42:11

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/19202165/overriding-the-physical-menu-button-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!