我正在制作一个应用程序,一个游戏,我希望玩家能够使用后退按钮进行跳跃(对于单点触控设备)。我的目标平台是 2.1(API 级别 7)。
我已经尝试了 onKeyDown() 和 onBackPressed(),但是它们只在后退按钮被释放时被调用,而不是在它被按下时被调用。
1) 这正常吗?
2)我怎样才能让它在按下按钮时注册按下?
编辑: 我还想补充一点,它可以使用键盘正常工作(按下某个键时会调用 onKeyDown)。
最佳答案
更新:我对此很好奇。看看android.view.View源码:http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/view/View.java
a typical example would be handling the BACK key to update the application's UI instead of allowing the IME to see it and close itself.
代码:
/**
* Handle a key event before it is processed by any input method
* associated with the view hierarchy. This can be used to intercept
* key events in special situations before the IME consumes them; a
* typical example would be handling the BACK key to update the application's
* UI instead of allowing the IME to see it and close itself.
*
* @param keyCode The value in event.getKeyCode().
* @param event Description of the key event.
* @return If you handled the event, return true. If you want to allow the
* event to be handled by the next receiver, return false.
*/
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
return false;
}
使用 dispatchKeyEvent:
@Override
public boolean dispatchKeyEvent (KeyEvent event) {
Log.d("**dispatchKeyEvent**", Integer.toString(event.getAction()));
Log.d("**dispatchKeyEvent**", Integer.toString(event.getKeyCode()));
if (event.getAction()==KeyEvent.ACTION_DOWN && event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
Toast.makeText(this, "Back button pressed", Toast.LENGTH_LONG).show();
return true;
}
return false;
}
独立记录两个事件,即使是后退键。出于某种原因,唯一没有记录的键是 KEYCODE_HOME
。事实上,如果您一直按下后退按钮,您将看到连续几个 ACTION_DOWN
(0) 事件(如果您改为 return false;
,则更多)。在 Eclair 模拟器和 Samsung Captivate(自定义 Froyo ROM)中测试。
关于Android 后退按钮覆盖帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5863767/