Android:如何将侦听器添加到硬件菜单按钮?
问题描述:
我目前正在尝试将点击侦听器添加到菜单硬件按钮.目前,我只是将onclick逻辑放入onCreatePanelMenu方法中并返回false.但这感觉不对.
I'm currently trying to add a click listener to the menu hardware button. Currently I'm just putting my onclick logic into the onCreatePanelMenu-method and return false. But that just feels wrong.
还有更干净的方法吗?
当前代码如下:
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
Toast.makeText(this, "HALLO!", Toast.LENGTH_SHORT).show();
return false;
}
答
Catch the key event inside onKeyDown()
and add your action there.
示例:
@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
switch(keycode) {
case KeyEvent.KEYCODE_MENU:
doSomething();
return true;
}
return super.onKeyDown(keycode, e);
}
只需将 doSomething()
替换为您的功能/方法.
Just replace doSomething()
with your functionality/methods.