keinabel
keinabel

Reputation: 1042

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

In my current View, a keyboard is open with numbers 0 to 9, a delete key and an enter key. I added both an onKeyDown and an onKeyUp event. Both should log the keycode to the debug console when pressed.

@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;
}

I pressed every single key on the keyboard with the following result:

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

Can someone explain why the keydown event is never triggered for 0-9 and enter? I really need it to trigger when 0-9 are pressed.

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?

Upvotes: 5

Views: 4692

Answers (2)

Yurii Tsap
Yurii Tsap

Reputation: 3744

To understand the workflow you need to dive inside the code a little bit, it's not so obvious but nevertheless. Your particular case depends on which view you are extending and the IME. From 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.

You can use TextWatcher - this is a good solution, but I'm not aware of your needs. In any case if you are overriding onKeyDown() - it will be triggered, and you need to handle it by yourself or call parent implementation. In the case with EditText - onKeyDown will be handled by TextView, despite few cases(Back Button i.e.).

Upvotes: 1

keinabel
keinabel

Reputation: 1042

I only found a solution to work around this issue, but I did not find the reason WHY this happens in the first place.

This code did the job:

@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;
}

Upvotes: 5

Related Questions