Android - Get keyboard key press

Bemipefe picture Bemipefe · Jun 30, 2012 · Viewed 48.8k times · Source

I want to catch the press of any key of the softkeyboard. I don't want a EditView or TextView in my Activity, the event must be handled from a extended View inside my Activity.

I just tried this:

1) Override the onKeyUp(int keyCode, KeyEvent event) Activity method. This don't work with softkeyboard, it just catch few hardkeyboard.

2) Create my OnKeyListener and register that in my View that contains a registered and working OnTouchListener. This doesn't work at all with softkeyboard.

3) Override the onKeyUp(int keyCode, KeyEvent event) View method. This not work at all neither if I set my OnKeyListener nor if I don't set it.

4) With the InputMethodManager object Call the method showSoftInput and passing it my View. This don't work neither for raise up the keyboard, indeed i have to call toggleSoftInput; nor to catch the key events.

I tested all only in the emulator but i think it's enough. Why it's so complicate take a simple key event from a keyboard ?

Answer

vasart picture vasart · Jun 30, 2012

For handling hardware keys and Back key you could use dispatchKeyEvent(KeyEvent event) in your Activity

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    Log.i("key pressed", String.valueOf(event.getKeyCode()));
    return super.dispatchKeyEvent(event);
}

UPD: unfortunately you can't handle soft keyboard events (see Handle single key events), unless you develop your own custom keyboard (follow the link to learn how Creating input method).