我正在制作应用程序,游戏,我希望玩家能够使用后退按钮进行跳转(对于单点触控设备)。我的目标平台是2.1(API级别7)。
我已经尝试过onKeyDown()和onBackPressed(),但只有当后退按钮是RELEASED时才调用它们,而不是在按下它时。
1)这是正常的吗?
2)如何在按下按钮时注册按键?
编辑: 我还想补充说它使用键盘正常工作(按下键时会调用onKeyDown)。
答案 0 :(得分:1)
更新:我对此感到好奇。看一下android.view.View源代码:http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/view/View.java
典型的例子是处理BACK键来更新应用程序的UI,而不是让IME看到它并自行关闭。
代码:
/**
* 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模拟器和三星Captivate(自定义Froyo ROM)中测试。