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.
I will give another option so you don't have to subclass EditText. Create an
InputFilter
that filters out linebreaks. Then useEditText.addInputFilter
.Source code for such an input filter is here: https://gist.github.com/CapnSpellcheck/7c72830e43927380daf5205100c93977
You can pass 0 in the constructor, and it won't allow any newlines. Also, you can combine this with one of the other tweaks such as
android:imeOptions="actionDone"
, as this will help improve the experience on some devices.This is a method, where you don't have to override the EditText class. You just catch and replace the newlines with empty strings.
Adding this property to the
EditText
XML works for me:It lets the users input newline characters but the
EditText
itself does not increase in height.The answer provided by @Andreas Rudolph contains a critical bug and shouldn't be used. The code causes an
IndexOutOfBoundsException
when you past text inside theEditText
which contains multiple new-line characters. This is caused by the type of loop which is used, theEditable
object will call theafterTextChanged
method as soon as its contents change (replace, delete, insert).Correct code:
I'm testing this and it seems to work: