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

Randy Sugianto 'Yuku' picture Randy Sugianto 'Yuku' · May 20, 2011 · Viewed 64.1k times · Source

How do I make an EditText on Android such that the user may not enter a multi-line text, but the display is still multi-line (i.e. there is word-wrap instead of the text going over to the right)?

It's similar to the built-in SMS application where we can't input newline but the text is displayed in multiple lines.

Answer

Tony the Pony picture Tony the Pony · May 20, 2011

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