Get back key event on EditText

Flávio Faria picture Flávio Faria · Feb 25, 2011 · Viewed 39.2k times · Source

How can I handle the event of pressing back key while typing on an EditText? When the virtual keyboard is shown and the user presses back, it gets hidden. I want to handle this event, but setting an OnKeyListener in the EditText does not help.

Answer

Flávio Faria picture Flávio Faria · Feb 25, 2011

Thank you Reno. It probably seems to work, but I managed to solve it differently.

I overrode EditText's onKeyPreIme(int keyCode, KeyEvent event). This method intercepts keypresses on the IME. =D

public boolean onKeyPreIme(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && 
        event.getAction() == KeyEvent.ACTION_UP) {
            // do your stuff
            return false;
    }
    return super.dispatchKeyEvent(event);
}