覆盖在Android上的物理菜单按钮按钮、菜单、物理、Android

2023-09-07 12:34:54 作者:单车。

我想我的Andr​​oid设备上的菜单键打开打开菜单,而我的应用程序正在运行的对话,而不是。我试图$ C C的$成 onCreateOptionsMenu(菜单菜单),但只在第一次我pressed菜单按钮的工作。我可以做一些其他的方式?

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?

推荐答案

您可以通过截取他们的活动覆盖了系统的关键presses的默认行为。这是通过覆盖完成的onKeyDown事件中,并返回如果你想prevent从系统正在处理的关键。在$ C $下你的情况看起来应该如下:

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

这可能不是因为虽然所有键的工作;这样做的原因是,键发送到当前视图活动收到此消息。在这种情况下,你需要重写的onkeydown 当前来看也是如此。

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.