views:

333

answers:

2

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 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...

+1  A: 

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

Konstantin Burov
That helps - one layer of mist gone!
Dizzley
A: 

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.

Maragues
Yeah - MENU and BACK work fine but KEYCODE_0, KEYCODE_1... and KEYCODE_ENTER don't trigger. I see code for onEditorAction which reacts to ENTER but do I have to trap that separately? Sorry if I confused you. I think your code is a good start... You have to consider repeats, cancels, longpresses etc. (depending on OS version). Still looking for a pointer to a comprehensive discussion.
Dizzley
IME operations are not generally raw key events; they are edit operations on an InputConnection that was retrieved from the current focus view. (TextView/EditText has an implementation for editing its text). You can get raw events *instead* by putting focus on a view that doesn't supply an InputConnection... however this will significantly limit the functionality of the keyboard.
hackbod