Android:拦截onKeyDown()和onKeyUp()

时间:2015-05-06 12:44:27

标签: java onkeydown intercept

我想从硬件键盘拦截关键事件。例如,当用户按下“a”时,我不希望它是用EditText编写的。因此,当按下并释放“a”键时,我返回true,但无论如何它都写在EditText中。有什么问题?

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_A:
            //Here it logs correct, but the letter appears in the EditText anyway
            Log.d("Textboard","A");
            return true;

        default:
            return super.onKeyDown(keyCode, event);
    }
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_A:
            //Here it logs correct, but the letter appears in the EditText anyway
            Log.d("Textboard","A");
            return true;

        default:
            return super.onKeyUp(keyCode, event);
    }
}

1 个答案:

答案 0 :(得分:0)

活动的onKeyXXX()晚于EditText的onKeyXXX()调用。

如果要拦截它,只需覆盖dispatchKeyEvent()