简体   繁体   中英

Android: Intercept onKeyDown() and onKeyUp()

I want to intercept key events from a hardware keyboard. For example when the users presses "a" I do not want that it is written in an EditText. Therefore I return true when the "a"-key is pressed and released but it is written in the EditText anyway. What is wrong?

@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);
    }
}

onKeyXXX() of an activity is called later than onKeyXXX() of the EditText.

If you want to intercept it, just override the dispatchKeyEvent() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM