Get back key event on EditText

I have no idea why this is the case but OnKeyListener works if you just purely override onKeyPreIme on your custom EditText.

customEditText.setOnKeyListener((v, keyCode, event) -> {
            if(event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        getPresenter().onBackPressed();
                        break;
                }
            }
            return false;
        }); 

@Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        return super.dispatchKeyEvent(event);
    }

This does not work ?

edText.setOnKeyListener(new OnKeyListener()
    {
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if (event.getAction() == KeyEvent.ACTION_DOWN)
            {
                //check if the right key was pressed
                if (keyCode == KeyEvent.KEYCODE_BACK)
                {

                    return true;
                }
            }
            return false;
        }
    });

EDIT :

Alright this is depressing. Android does not send IME events on closure of the qwerty keypad. This is the only workaround that ive come across. I hope it works for you as well.


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