How to catch a "Done" key press from the soft keyboard

I am not quite sure which kind of listener was used in the accepted answer. I used the OnKeyListener attached to an EditText and it wasn't able to catch next nor done.

However, using OnEditorActionListener worked and it also allowed me to differentiate between them by comparing the action value with defined constants EditorInfo.IME_ACTION_NEXT and EditorInfo.IME_ACTION_DONE.

editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if ((actionId & EditorInfo.IME_MASK_ACTION) != 0) {
            doSomething();
            return true;
        }
        else {
            return false;
        }
    }
});

@Swato's answer wasn't complete for me (and doesn't compile!) so I'm showing how to do the comparison against the DONE and NEXT actions.

editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
        int result = actionId & EditorInfo.IME_MASK_ACTION;
        switch(result) {
        case EditorInfo.IME_ACTION_DONE:
            // done stuff
            break;
        case EditorInfo.IME_ACTION_NEXT:
            // next stuff
            break;
        }
    }
});

Also I want to point out that for JellyBean and higher OnEditorActionListener is needed to listen for 'enter' or 'next' and you cannot use OnKeyListener. From the docs:

As soft input methods can use multiple and inventive ways of inputting text, there is no guarantee that any key press on a soft keyboard will generate a key event: this is left to the IME's discretion, and in fact sending such events is discouraged. You should never rely on receiving KeyEvents for any key on a soft input method.

Reference: http://developer.android.com/reference/android/view/KeyEvent.html

Tags:

Android