Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android onKeyDown not catching Dpad center and enter key presses

Doing a simple override in my base activity of onKeyDown, I'm able to capture all key presses except those of the enter and dpad center buttons (as determined via breakpoint). I've no clue as to why - can anyone shed some light on the situation?

EDIT: Quick update - it does capture Dpad center and enter key LONG presses, but still not normal presses.

like image 259
user1403565 Avatar asked Jul 20 '12 00:07

user1403565


2 Answers

I know this question is already pretty old but in case some desperate coder got lost I post my answer.

I had a similar problem with my USB keyboard. When anything else except a EditText box was focussed the ENTER key was never caught by onKeyUp or onKeyDown.

if you use dispatchKeyEvent() you get the KeyEvent before it reaches the window and in my case I definitely get the ENTER key. But cautious, the event is called twice, once for key down and once for key up.

here a sample code:

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    System.out.println(event.getAction() + " " + event.getKeyCode() + " - " + (char) event.getUnicodeChar());

    return true;
}
like image 124
tagtraeumer Avatar answered Oct 15 '22 01:10

tagtraeumer


Did you read the documentation?

Key presses in software keyboards will generally NOT trigger this listener, although some may elect to do so in some situations. Do not rely on this to catch software key presses.

Also, your way of capturing keys is very vague. You are not even checking the keyCode sent to you by using:

@Override public boolean onKeyDown(int keyCode, KeyEvent event) { return false; }

You can handle onKey from a View:

public boolean onKey(View v, int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_ENTER:
            /* This is a sample for handling the Enter button */
            return true;
    }
    return false;
}

Remember to implement OnKeyListener and to set your listener

viewname.setOnKeyListener(this);
like image 1
Erol Avatar answered Oct 15 '22 00:10

Erol