Search code examples
androidviewfocuskeyevent

Android: how to prevent foucs change while press navigation key?


For some special reason, I have to manage focus all by myself.
In emulator, KeyEvent.KEYCODE_DPAD_DOWN and UP were assigned to move focus. To get things right, I prototyped like below

public class Button extends android.widget.Button {

public Button(Context context) {
    super(context);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (isPreventSystemBehavior(keyCode)) {

        return true;
    }

    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (isPreventSystemBehavior(keyCode)) {
        return true;
    }

    return super.onKeyUp(keyCode, event);
}

private boolean isPreventSystemBehavior(int keyCode) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_DPAD_DOWN:
    case KeyEvent.KEYCODE_DPAD_UP:
    case KeyEvent.KEYCODE_DPAD_LEFT:
    case KeyEvent.KEYCODE_DPAD_RIGHT:
        return true;
    }

    return false;
}
}

It worked. But for EditText case, KeyEvent.KEYCODE_DPAD_LEFT/RIGHT shouldn't be stopped. Then I have to get every view/widget to implement their own onKeyDown/Up, which is tedious. Is there any easier way to do this? Thanks.


Solution

  • After checked out source code, finally I ended up with following solution, really simple,

    @Override
    public boolean executeKeyEvent(KeyEvent event) {
        return true;
    }
    

    Simply overrode ScrollView::executeKeyEvent and return true