Search code examples
androidfocuskeyevent

Android: No KeyEvent on unfocusable view?


In my case, I'm required to intercept all key events before they are dispatched to target. So I installed a KeyListener on every view or widget, Activity.onKey can't satisfy me in the case.

However, I found that if view (like RelativeLayout) is not focusable, it won't receive any KeyEvent. And I also got following warnings

WARN/KeyCharacterMap(312): No keyboard for id 0
WARN/KeyCharacterMap(312): Using default keymap: /system/usr/keychars/qwerty.kcm.bin

If I forced view to be focusable, it's going to receive KeyEvent. I'm curious about this phenomenon. I've no idea about if system never sends KeyEvents to view which is unfocusable or just I used wrong way to intercept key events.


Solution

  • To do this use dispatchKeyEvent (see http://developer.android.com/reference/android/view/Window.Callback.html#dispatchKeyEvent%28android.view.KeyEvent%29) on the Activity. This should receive every KeyEvent. You can do any modifications and then call super.dispatchKeyEvent if you want the standard processing to kick in.