开发者

Confused about Android key event handling. Any good explanations?

I'm a relative beginner with Android. Does anybody have a sane explanation for how to listen for keys and soft keys in an EditText/TextView?

I'd love to see a comprehensive tutorial or set of examples.

As I understand it, I can add a KeyListener to my Activity, e.g. onKeyDown(), onKeyUp() but when I try this I can't trigger the events for normal keys only HOME and BACK for example.

I have seen mention of using a开发者_JAVA技巧 TextWatcher but that isn't the same as handling raw key events.

There seem to be a number of half-solutions here on SO. Hoping you can help clear the mists of confusion...


You have to assign a key listener not to activity but rather to EditText itself.


This is what I have to listen to BACK or MENU key events. Simply add this method, without implementing any Interface. I do this in my BaseActivity, from which every Activity inherits.

public boolean onKeyDown(int keyCode, KeyEvent event) {
    Log.d(NAME, "Key pressed");

    switch (keyCode) {
    case KeyEvent.KEYCODE_BACK:
        Log.d(NAME, "Back pressed");
        // IGNORE back key!!
        return true;
        /* Muestra el Menú de Opciones */
    case KeyEvent.KEYCODE_MENU:
        Intent menu = new Intent(this, Menu.class);

        // start activity
        startActivity(menu);
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

PS: I highly discourage ignoring the back key.


For example:

myEditText.setOnKeyListener(new OnKeyListener() {
     public boolean onKey(View v, int keyCode, KeyEvent event) {
         if (event.getAction() == KeyEvent.ACTION_DOWN)
             if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
                //your code here
             }
         return false;
     }
});


I recently found another way that be stuck using Activity onKeyDown, or event setting a key listener on view (which is not really working with key events from ADB in my case) with view.setOnKeyListener.

Since android P method addOnUnhandledKeyEventListener has been introduced. It allows you to do whatever you need to do when your view is able to catch unhandled key events.

Here is an example of how I used it :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) yourView.addOnUnhandledKeyEventListener { v, event ->
    when (event.keyCode) {
        KeyEvent.KEYCODE_UNKNOWN -> {
            TODO("Do whatever you need to do.")
            true // Specify you did handle the event
        }
        KeyEvent.KEYCODE_SOFT_RIGHT -> {
            TODO("Do whatever you need to do.")
            true // Specify you did handle the event
        }
        // etc...
        else -> false // Specify you didn't handle the event
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜