Reputation: 341
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!
Upvotes: 4
Views: 1936
Reputation: 31
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:
new Thread(new Runnable() {
@Override
public void run() {
Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_UP);
}
}).start();
Upvotes: 2
Reputation: 1444
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).
Upvotes: 0