onKeyDown 事件第一次没有被调用?
我有一个 onKeyDown 事件,它无法识别第一次按键(甚至不会输入该事件,我已经通过生成“toast”输出进行了测试)。在第二次按键及之后,它工作得很好。如果我单击屏幕上的另一个元素并再次尝试按键,则再次需要按下另一个按键才能启动。这是代码:
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
scorered.performClick();
return true;
case KeyEvent.KEYCODE_1:
red_m1.performClick();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
scoreblue.performClick();
return true;
case KeyEvent.KEYCODE_2:
blue_m1.performClick();
return true;
case KeyEvent.KEYCODE_BACK:
finish();
return true;
}
return true;
}
我已经被难住了好几个小时,所以非常感谢任何帮助!
I have an onKeyDown event which wont recognise the first key press (wont even enter the event, i have tested by producing a 'toast' output). On the second key press and after, it works perfectly. If I click on another element on the screen and try the key press again, it yet again needs another key press to get it going. Here is the code:
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
scorered.performClick();
return true;
case KeyEvent.KEYCODE_1:
red_m1.performClick();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
scoreblue.performClick();
return true;
case KeyEvent.KEYCODE_2:
blue_m1.performClick();
return true;
case KeyEvent.KEYCODE_BACK:
finish();
return true;
}
return true;
}
I have been stumped for hours so any help is much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我确信,这种行为有充分的理由,但不认为消除焦点是一个好的解决方案。我的解决方法是触发一个 keydown 事件,“激活”常规的 onKeyDown 功能。这是片段:
I'm sure, there are good reasons for such behaviour, but do not think, that removing focus is a good solution. My workaround is to fire a keydown event, that "activate" regular onKeyDown functionality. Here is snippet:
要解决此问题,解决方法是在按任何 DPAD 键之前移除视图焦点。它适用于我的情况。我遇到了完全相同的问题:当 Android Activity 的视图获得焦点时,第一个 DPAD 键事件(即
KeyDown
事件)被忽略:这些方法都不会被调用:<代码>onUserInteraction()、dispatchKeyEvent()
、onKeyDown()
。但是,可以捕获后续 DPAD 按键事件 -KeyUp
、KeyDown
、KeyUp
...。请注意,软键(主页、上一个、最近)和硬按钮(BUTTON_A、BUTTON_B、BUTTON_X、BUTTON_Y)不会出现此问题。
To fix this, a work-around is to remove the view focus before pressing any DPAD key. It works in my case. I am having exactly the same issue: When a view of Android Activity is on focus, the very first DPAD key event, that is, the
KeyDown
event, is ignored: None of these methods are called:onUserInteraction()
,dispatchKeyEvent()
,onKeyDown()
. However, subsequent DPAD key events -KeyUp
,KeyDown
,KeyUp
, ..., can be captured.Note that this issue does not occur with soft keys (Home, Previous, Recents) nor with hard button keys (BUTTON_A, BUTTON_B, BUTTON_X, BUTTON_Y).