75

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.

1
  • 11
    just add android:inputType="textPersonName" to the EditText it will stop it from pressing enter May 21, 2014 at 11:06

19 Answers 19

49

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);
    }
}
7
  • 4
    Should this line: return super.onKeyDown(keyCode, event); be in onKeyDown or am I imagining? :P
    – necixy
    May 20, 2011 at 11:04
  • We both are working for same community. You're welcome jen. :)
    – necixy
    May 20, 2011 at 11:16
  • 11
    Thanks for your answer. (I upped the other answer too). Tip: you can avoid subclassing by just editText.setOnKeyListener(...) and return (keyCode == KeyEvent.KEYCODE_ENTER). May 23, 2011 at 3:09
  • 2
    enter key is still working in nexus with linear layout Feb 11, 2014 at 4:26
  • 6
    Almost no keyboards actually send key events. Those are meant for hardware keys. They almost all use commitText, which will not call this function. Jun 15, 2017 at 20:59
49

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.

4
  • 3
    +1 This was more useful in my case than the accepted answer, for the simple reason, that I can use it as a default implementation of TextWatcher, which can be expanded by subclasses (Which would then simply call super.afterTextChanged(...) to retain that check for line breaks. Works !
    – AgentKnopf
    Jul 11, 2012 at 10:42
  • 1
    For-loop condition should be i > 0 rather than i >= 0. When i == 0, s.subSequence(i-1, i) gets an IndexOutOfBoundsException.
    – TalkLittle
    Nov 4, 2014 at 22:01
  • 2
    I think this throws an IndexOutOfBoundsException for text with new line that is copy and pasted in with multiple new line characters.
    – Chriskot
    Mar 24, 2015 at 0:17
  • 1
    @TalkLittle I posted another answer with the correct code, only changing the for loop condition doesn't fix the IndexOufOfBoundsException. See my answer: stackoverflow.com/a/36485266/1052697
    – Rolf ツ
    Apr 7, 2016 at 19:20
23

Property in XML

android:lines="5"
android:inputType="textPersonName"
2
  • Thanks, the simplest! Although I noticed it prevented my click listener on the ET from working... so use editText.setSingleLine(false); instead if so.
    – Azurespot
    May 13, 2016 at 7:00
  • This is totally dependent on the keyboard used. Many will still show an enter key Jun 15, 2017 at 21:00
14

This one works for me:

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

It shows a smiley instead of the Enter key.

3
  • 2
    From experience this does not work on every keyboard. A HTC phone we had around still displayed the enter key.
    – Treeline
    Mar 18, 2015 at 14:38
  • This is totally dependent on the keyboard used. Many will still show an enter key Jun 15, 2017 at 20:59
  • If you long press on the smiley button in a Nexus 6, then you are still able to add a line break. Thus this is no general solution then.
    – Elementary
    Nov 9, 2017 at 17:04
10

Here's a more correct answer that does not display the enter key on the IME keyboard:

// IMPORTANT, do this before any of the code following it
myEditText.setSingleLine(true);

// IMPORTANT, to allow wrapping
myEditText.setHorizontallyScrolling(false);
// IMPORTANT, or else your edit text would wrap but not expand to multiple lines
myEditText.setMaxLines(6);

Also, you may replace setSingleLine(true) with either, an explicit android:inputType on the XML layout file, or setInputType(InputType.*) on code – in which, the input type used, is anything that you know restricts the input to single lines only (i.e., anything that calls setSingleLine(true) implicitly already).


Explanation:

What setSingleLine(true) does is calling setHorizontallyScrolling(true) and setLines(1) implicitly, alongside with altering some IME keyboard settings to disable the enter key.

In turn, the call to setLines(1) is like calling setMinLines(1) and setMaxLines(1) in one call.

Some input types (i.e., the constants from InputType.TYPE_*) calls setSingleLine(true) implicitly, or at least achieves the same effect.

Conclusion:

So to achieve what the OP wants, we simply counter those implicit settings by reverting those implicit calls.

0
8

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 the EditText which contains multiple new-line characters. This is caused by the type of loop which is used, the Editable object will call the afterTextChanged method as soon as its contents change (replace, delete, insert).

Correct code:

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;
            }
        }
    }
});
7
  • You should have edited the answer, instead of making a new one. Dec 14, 2016 at 19:47
  • @RobertMartin I was wondering this myself and asked for help on the Meta website, they suggested that I should post a new answer. Because the changes I would have made conflicted with the author's original intends.
    – Rolf ツ
    Dec 14, 2016 at 20:04
  • 1
    Nice! However, if you start by hitting the Enter key you'll still have a new line at the beginning (so i>=0 should work) ^^
    – Blo
    Jan 18, 2017 at 22:13
  • Nice Solution. For someone looking for code in Kotlin : for (i in s.length - 1 downTo 0) { if(s[i] == '\n') { s.delete(i, i + 1) return } } Sep 27, 2019 at 7:08
  • 1
    Done @Rolfツ! Thanks for the improvement Jul 6, 2020 at 14:38
5

I'm testing this and it seems to work:

EditText editText = new EditText(context);
editText.setSingleLine(false);
editText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT);
2
  • Awesome thanks. Setting anything in the XML was disabling my ET click listeners... so doing it this way did not! The return key on the keyboard changes into a "Done" button. (I only needed the editText.setSingleLine(false);).
    – Azurespot
    May 13, 2016 at 6:59
  • This is totally dependent on the keyboard used. Many will still show an enter key Jun 15, 2017 at 21:01
5

Try this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_ENTER)
    {
        //Nothing
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
2
  • 2
    No. This constrains the edit to a single line. The OP wants multiple lines; he just doesn't want the user to be able to enter line breaks. May 20, 2011 at 10:59
  • Almost no keyboards actually send key events. Those are meant for hardware keys. They almost all use commitText, which will not call this function. Jun 15, 2017 at 21:00
3

You can set it from the xml like this:

android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="10"

don't forget android:inputType="text", if you don't set it, it doesn't work. I don't know why though. Also don't forget to change maxLines to your preferred value.

1
  • This is totally dependent on the keyboard used. Many will still show an enter key Jun 15, 2017 at 21:01
3

Simply add

        android:singleLine="true"

to your EditText

1
  • 3
    This is deprecated!
    – Blasco73
    May 17, 2017 at 17:15
2

Here is the solution....

<EditText
   android:id="@+id/editText"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:maxLength="150"                                 
   android:textSize="15dp"
   android:imeOptions="actionDone"
   android:inputType="text|textMultiLine"/>

Usage in java class

editText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, 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 (keyCode == KeyEvent.KEYCODE_ENTER);
        }
    });
2
  • Welcome to SO. Thanks for your answer. Could you format it properly, please, e.g. by seperating text and code part as Here is the solution...? Some more background information is also helpful. Thanks.
    – CKE
    Sep 12, 2018 at 8:49
  • You already return true when keyCode==KeyEvent.KEYCODE_ENTER. So, next will return false.
    – CoolMind
    Jun 10, 2021 at 12:22
1

The accepted answer worked so well until I copied text with line-breaks into into the EditText. So I added onTextContextMenuItem to monitor the paste action.

@Override
public boolean onTextContextMenuItem(int id) {
    boolean ret = super.onTextContextMenuItem(id);
    switch (id) {
        case android.R.id.paste:
            onTextPaste();
            break;
    }
    return ret;
}

public void onTextPaste() {
    if (getText() == null)
        return;
    String text = getText().toString();
    text = text.replaceAll(System.getProperty("line.separator"), " ");
    text = text.replaceAll("\\s+", " ");
    setText(text);
}
1

You can change the action button from code

editText.imeOptions = EditorInfo.IME_ACTION_DONE
editText.setRawInputType(InputType.TYPE_CLASS_TEXT)

Xml

android:inputType="textMultiLine"
0
<EditText 
  android:id="@+id/Msg"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"              
  android:layout_marginTop="5dip"
  android:lines="5"
  android:selectAllOnFocus="true"               
  android:hint="Skriv meddelande...\n(max 100tkn)"/>


EditText et = (EditText)findViewById(R.id.Msg);
String strTmp = et.getText().toString();
strTmp = strTmp.replaceAll("\\n"," ");
0
    EditText textView = new EditText(activity);
    ...
    textView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
            if(KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode()) {
                return false;
            }
            ....... 

        }
    });
0

For a URI you could use:

android:inputType="textUri"
android:lines="1"
android:maxLength="128"

Otherwise android:inputType="textPersonName" as mentioned above works for other EditText such user name, etc.

0

I will give another option so you don't have to subclass EditText. Create an InputFilter that filters out linebreaks. Then use EditText.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.

0
/**
 * Set the EditText to multiline
 * Starting with one line and expanding to maxLines = line
 * the next action will be force to IME_ACTION_NEXT
 */
fun TextInputEditText.setMultilineTextNextAction(lines: Int) {
    imeOptions = EditorInfo.IME_ACTION_NEXT
    setRawInputType(InputType.TYPE_CLASS_TEXT)
    maxLines=lines
}

ALso, control the length of input text with android:maxLength, as:

 <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/textEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:textAppearance="@style/WmTextBody"
            android:gravity="top"
            android:imeOptions="actionNext"
            android:maxLength="100"
            />
-1

Adding this property to the EditText XML works for me:

android:lines="1"

It lets the users input newline characters but the EditText itself does not increase in height.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.