Android - 为什么 onKeyUp 会触发 KeyEvent 而 onKeyDown 不会?

Android - Why does onKeyUp trigger a KeyEvent, but onKeyDown does not?

在我当前的视图中,打开了一个键盘,其中包含数字 0 到 9、一个删除键和一个回车键。 我添加了一个 onKeyDown 和一个 onKeyUp 事件。两者都应在按下时将键码记录到调试控制台。

@Override
public boolean onKeyDown(int pKeyCode, KeyEvent pKeyEvent) {
    Log.d("KEYDOWN", pKeyCode+"");
    return true; // also tried false
}
@Override
public boolean onKeyUp(int pKeyCode, KeyEvent pKeyEvent) {
    Log.d("KEYUP", pKeyCode+"");
    return true;
}

我按了键盘上的每个键,结果如下:

D/KEYUP: 8
D/KEYUP: 9
D/KEYUP: 10
D/KEYUP: 11
D/KEYUP: 12
D/KEYUP: 13
D/KEYUP: 14
D/KEYUP: 15
D/KEYUP: 16
D/KEYDOWN: 67
D/KEYUP: 67
D/KEYUP: 7
D/KEYUP: 66

谁能解释一下为什么 0-9 的 keydown 事件永远不会触发并输入?我真的需要它在按下 0-9 时触发。

EDIT: I added a solution that fixed the issue by replacing both functions with dispatchKeyEvent. This doesn't explain why onKeyDowndidn't recognize those keys, though.

Someone got an answer for this?

我只找到了解决此问题的解决方案,但我并没有首先找到发生这种情况的原因。

这段代码完成了工作:

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getAction()==KeyEvent.ACTION_DOWN) {
        Log.d("KEYDOWN", event.getKeyCode()+"");
    }
    else if (event.getAction()==KeyEvent.ACTION_UP) {
        Log.d("KEYUP", event.getKeyCode()+"");
    }
    Log.d("KEY", event.getKeyCode()+"");
    return false;
}

要了解工作流程,您需要深入了解代码,虽然不是很明显,但仍然如此。您的具体情况取决于您要扩展的视图和 IME。来自 docs :

In general, the framework cannot guarantee that the key events it delivers to a view always constitute complete key sequences since some events may be dropped or modified by containing views before they are delivered. The view implementation should be prepared to handle FLAG_CANCELED and should tolerate anomalous situations such as receiving a new ACTION_DOWN without first having received an ACTION_UP for the prior key press.

您可以使用 TextWatcher - 这是一个很好的解决方案,但我不知道您的需求。在任何情况下,如果您重写 onKeyDown() - 它将被触发,您需要自己处理或调用父实现。在使用 EditText 的情况下 - onKeyDown 将由 TextView 处理,尽管有少数情况(后退按钮即)。