开发者

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

开发者 https://www.devze.com 2023-03-08 10:21 出处:网络
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

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 isPreventSystem开发者_如何学PythonBehavior(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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消