EditText maxLines not working - user can still enter more lines than set

<EditText android:id="@+id/editText2" android:layout_height="wrap_content" android:layout_width="fill_parent" android:maxLines="5" android:lines="5"> </EditText> 

User can enter more than 5 lines by pressing enter / next line. How can I limit user input to a fixed number of lines using EditText?

+75
android android-layout android-edittext
Aug 17 '11 at 12:41
source share
13 answers

The maxLines attribute corresponds to the maximum height of the EditText , it controls the outer borders, not the inner text lines.

+55
Aug 17 2018-11-18T00:
source share
 <EditText android:id="@+id/edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" android:maxLines="1" /> 

You just need to make sure that you have the "inputType" attribute set. This does not work without this line.

 android:inputType="text" 
+127
Dec 09 '16 at 7:48
source share

This does not solve the general problem of limiting n lines. If you want to limit EditText to just one line of text, this can be very simple.
You can install this in the xml file.

 android:singleLine="true" 

or programmatically

 editText.setSingleLine(true); 
+58
Nov 19 '11 at 5:50 a.m.
source share

@Cedekasem you are right, there is no built-in line terminator. But I built my own, therefore, if anyone is interested, the code is below. Greetings.

 et.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { // if enter is pressed start calculating if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) { // get EditText text String text = ((EditText) v).getText().toString(); // find how many rows it cointains int editTextRowCount = text.split("\\n").length; // user has input more than limited - lets do something // about that if (editTextRowCount >= 7) { // find the last break int lastBreakIndex = text.lastIndexOf("\n"); // compose new text String newText = text.substring(0, lastBreakIndex); // add new text - delete old one and append new one // (append because I want the cursor to be at the end) ((EditText) v).setText(""); ((EditText) v).append(newText); } } return false; } }); 
+23
Aug 18 2018-11-11T00:
source share

I did what you guys were looking for. Here is my class LimitedEditText .

Features:

  • you can limit the number of rows in the LimitedEditText component
  • you can limit the number of characters in the LimitedEditText component
  • If you exceed the limit of characters or lines somewhere in the middle of the text, the cursor will not lead you to the end - it will remain where you were.

Im disables the listener because every call to the setText() method recursively calls these three callback methods if the user has exceeded the character or string limit.

the code:

 import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.Log; import android.widget.EditText; import android.widget.Toast; /** * EditText subclass created to enforce limit of the lines number in editable * text field */ public class LimitedEditText extends EditText { /** * Max lines to be present in editable text field */ private int maxLines = 1; /** * Max characters to be present in editable text field */ private int maxCharacters = 50; /** * application context; */ private Context context; public int getMaxCharacters() { return maxCharacters; } public void setMaxCharacters(int maxCharacters) { this.maxCharacters = maxCharacters; } @Override public int getMaxLines() { return maxLines; } @Override public void setMaxLines(int maxLines) { this.maxLines = maxLines; } public LimitedEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.context = context; } public LimitedEditText(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } public LimitedEditText(Context context) { super(context); this.context = context; } @Override protected void onFinishInflate() { super.onFinishInflate(); TextWatcher watcher = new TextWatcher() { private String text; private int beforeCursorPosition = 0; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //TODO sth } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { text = s.toString(); beforeCursorPosition = start; } @Override public void afterTextChanged(Editable s) { /* turning off listener */ removeTextChangedListener(this); /* handling lines limit exceed */ if (LimitedEditText.this.getLineCount() > maxLines) { LimitedEditText.this.setText(text); LimitedEditText.this.setSelection(beforeCursorPosition); } /* handling character limit exceed */ if (s.toString().length() > maxCharacters) { LimitedEditText.this.setText(text); LimitedEditText.this.setSelection(beforeCursorPosition); Toast.makeText(context, "text too long", Toast.LENGTH_SHORT) .show(); } /* turning on listener */ addTextChangedListener(this); } }; this.addTextChangedListener(watcher); } } 
+10
May 03 '13 at 19:11
source share

I made a simpler solution for this: D

 // set listeners txtSpecialRequests.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { lastSpecialRequestsCursorPosition = txtSpecialRequests.getSelectionStart(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { txtSpecialRequests.removeTextChangedListener(this); if (txtSpecialRequests.getLineCount() > 3) { txtSpecialRequests.setText(specialRequests); txtSpecialRequests.setSelection(lastSpecialRequestsCursorPosition); } else specialRequests = txtSpecialRequests.getText().toString(); txtSpecialRequests.addTextChangedListener(this); } }); 

You can change the value of 3 in txtSpecialRequests.getLineCount() > 3 to suit your needs.

+7
Jun 08 '15 at 7:48
source share

Here is an InputFilter that limits valid lines in an EditText:

 /** * Filter for controlling maximum new lines in EditText. */ public class MaxLinesInputFilter implements InputFilter { private final int mMax; public MaxLinesInputFilter(int max) { mMax = max; } public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { int newLinesToBeAdded = countOccurrences(source.toString(), '\n'); int newLinesBefore = countOccurrences(dest.toString(), '\n'); if (newLinesBefore >= mMax - 1 && newLinesToBeAdded > 0) { // filter return ""; } // do nothing return null; } /** * @return the maximum lines enforced by this input filter */ public int getMax() { return mMax; } /** * Counts the number occurrences of the given char. * * @param string the string * @param charAppearance the char * @return number of occurrences of the char */ public static int countOccurrences(String string, char charAppearance) { int count = 0; for (int i = 0; i < string.length(); i++) { if (string.charAt(i) == charAppearance) { count++; } } return count; } } 

To add it to an EditText:

 editText.setFilters(new InputFilter[]{new MaxLinesInputFilter(2)}); 
+5
Nov 05 '14 at 16:45
source share

This is what I used in my project:

 editText.addTextChangedListener(new TextWatcher() { private String text; public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { text = arg0.toString(); } public void afterTextChanged(Editable arg0) { int lineCount = editText.getLineCount(); if(lineCount > numberOfLines){ editText.setText(text); } } }); editText.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // if enter is pressed start calculating if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){ int editTextLineCount = ((EditText)v).getLineCount(); if (editTextLineCount >= numberOfLines) return true; } return false; } }); 

And he worked in all scenarios

+4
Apr 18 '13 at 10:40
source share

getLineCount () - one of the options; if you want non-zero values, make sure your view is measured. For a soft keyboard, onKeyListener will not work, so you need to add addTextChangedListener (), which will track text changes as you type. Once you get enough lines inside your callbacks, do whatever you want to limit: remove characters from getText (), setText (), or something more fantastic. You can even limit the number of characters with a filter.

Another option is to control the size of the text using getLineBounds (). This will interact with text gravity / paddign, so be careful.

0
Feb 14 '13 at 1:09
source share

For the character limit, we can simply use the maxLength property for EditText, since it will not allow the user to enter more characters.

0
Apr 18 '13 at 12:27
source share

The simplest solution:

 android:maxLines="3" 

...

  @Override public void afterTextChanged(Editable editable) { // limit to 3 lines if (editText.getLayout().getLineCount() > 3) editText.getText().delete(editText.getText().length() - 1, editText.getText().length()); } 
0
Nov 29 '16 at 15:43
source share

Another way to limit EditText one line:

 editText2.setTransformationMethod(new SingleLineTransformationMethod()); 

Note that after applying this conversion method, the enter key creates spaces when pressed. This still satisfies the TS question.

0
Mar 21 '17 at 15:26
source share

Try using the following combination of EditText attributes inside the xml file:

android:singleLine="true"
android:maxLength="22"

-one
Dec 09 '16 at 8:57
source share



All Articles