1

我正在制作一个应用程序,一个游戏,我希望玩家能够使用后退按钮进行跳跃(对于单点触控设备)。我的目标平台是 2.1(API 级别 7)。

我已经尝试过 onKeyDown() 和 onBackPressed(),但它们仅在后退按钮被释放时调用,而不是在按下时调用。

1)这是正常的吗?

2)我怎样才能让它在按下按钮时注册按下?

编辑:我还想补充一点,它可以使用键盘正常工作(按下键时调用 onKeyDown)。

4

1 回答 1

1

更新:我对此感到好奇。看看android.view.View源代码: http: //grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/view/View。爪哇

一个典型的例子是处理 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 模拟器和 Samsung Captivate(自定义 Froyo ROM)中测试。

于 2011-05-03T00:24:24.870 回答