Listener for Done button on EditText?

Code is

final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
            Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }
});

In that 'edittext' is id of textfield

Check out this link Simply set setOnKeyListener to your editText


Dinash answer is nice, but it is not working on all devices. Below code works fine for all devices

edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }
});

The same Jone answer, but with replaced lambda:

etPointCombatFirst.setOnEditorActionListener((v, actionId, event) -> {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
                    return true;
                }
                return false;
            });

Kotlin Extension Solution

The base way to handle the done action in Kotlin is:

edittext.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        // Call onDone result here
        true
    }
    false
}

Kotlin Extension

Use this to call edittext.onDone {/*action*/} in your main code. Keeps it more readable and maintainable

edittext.onDone { submitForm() }

fun EditText.onDone(callback: () -> Unit) {
    // These lines optional if you don't want to set in Xml
    imeOptions = EditorInfo.IME_ACTION_DONE
    maxLines = 1
    setOnEditorActionListener { _, actionId, _ ->
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            callback.invoke()
            true
        }
        false
    }
}

Don't forget to add these options to your edittext Xml, if not in code

<EditText ...
    android:imeOptions="actionDone"
    android:inputType="text"/>

If you need inputType="textMultiLine" support, read this post