Confuses Android event management. Any good explanations?

I am a relative newbie with Android. Does anyone have a reasonable explanation on how to listen to keys and soft keys in EditText / TextView?

I would like to see a comprehensive tutorial or many examples.

As I understand it, I can add KeyListener to my activity, for example. onKeyDown (), onKeyUp (), but when I try to do this, I can not trigger events for regular keys with only HOME and BACK, for example.

I saw a mention of using TextWatcher, but this is not the same as handling raw key events.

On SO, there seem to be a few half-solutions. Hoping you can help eliminate the fog of confusion ...

+3
source share
3 answers

You need to assign a key listener not to activity, but to EditText itself.

+2
source

This is what I should listen to with BACK or MENU events. Just add this method without using 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 really do not recommend ignoring the return key.

+2
source

For instance:

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;
     }
});
+1
source

Source: https://habr.com/ru/post/1765115/


All Articles