Prevent enter key on EditText but still show the text as multi-line


Property in XML

android:lines="5"
android:inputType="textPersonName"

This is a method, where you don't have to override the EditText class. You just catch and replace the newlines with empty strings.

edittext.addTextChangedListener(new TextWatcher() {

public void onTextChanged(CharSequence s, int start, int before, int count) {

}

public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

public void afterTextChanged(Editable s) {
    /*
     * The loop is in reverse for a purpose,
     * each replace or delete call on the Editable will cause
     * the afterTextChanged method to be called again.
     * Hence the return statement after the first removal.
     * http://developer.android.com/reference/android/text/TextWatcher.html#afterTextChanged(android.text.Editable)
     */
    for(int i = s.length()-1; i >= 0; i--){
        if(s.charAt(i) == '\n'){
            s.delete(i, i + 1);
            return;
        }
    }
}
});

Credit to Rolf for improvement on an earlier answer.


I would subclass the widget and override the key event handling in order to block the Enter key:

class MyTextView extends EditText
{
    ...
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode==KeyEvent.KEYCODE_ENTER) 
        {
            // Just ignore the [Enter] key
            return true;
        }
        // Handle all other keys in the default way
        return super.onKeyDown(keyCode, event);
    }
}

This one works for me:

<EditText
    android:inputType="textShortMessage|textMultiLine"
    android:minLines="3"
    ... />

It shows a smiley instead of the Enter key.