onKeyUp doesn't work for KEYCODE_DPAD_CENTER

3.1k Views Asked by At

I have 2 activities, where I overrided the onKeyUp event:

@Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        Log.d(TAG, "Key up: " + keyCode);
        return super.onKeyUp(keyCode, event);
     }

The first is the main activity of the application, the other one is secondary. The first works fine, but the second captures events for Left-Right-Up-Down but not for Center click. Why?

1

There are 1 best solutions below

3
On

Since you have a Gallery in your layout, take a look at: https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/Gallery.java#L1216 . It might be possible that the Gallery steals your DPAD_CENTER event (and also ENTER).

I suggest you to use Activity.dispatchKeyEvent(android.view.KeyEvent) to stop the event before it even goes to that Gallery.

Try using it like this (in your Activity):

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
  if(event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER) {
    // Do your stuff here.
    return true; // Consume the event (or not, your call)
  }
  return super.dispatchKeyEvent(event);
}