I want to allow use to enter just 5 lines, I tried this
<EditText
android:layout_below="@+id/tv_signup_descriptionError"
android:id="@+id/et_signup_description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:hint="@string/et_hint_enterDescription"
android:singleLine="false"
android:lines="5"
android:gravity="top"
android:scrollHorizontally="false"
android:inputType="textMultiLine"
android:maxLines="5"/>
but still I can press Enter
after the fifth line
You cannot do that using any XML attributes.
maxlines
represents the maximum height
of the EditText and not the number of input lines.
You can however implement your own code to check for the number of lines.
The following is not my own code, but is taken from this answer.
mEditText.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
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;
}
@Swayam you are right, But this solution has improved :
1- better performance
2- in your solution if you entered 7 lines (your max input lines) then pressed enter in Top lines the last line will be delete, But in this solution "enter" key has ignored.
mEditText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
if ( ((EditText)v).getLineCount() >= 7 )
return true;
}
return false;
}
});
The maxLines attribute is to limit height of the EditText. To limit maximum number of lines you have to do it yourself in code.
/** MAX_LINES You want to set */
public void afterTextChanged(Editable editable) {
int lines = mEditText.getLineCount();
if (lines > MAX_LINES) {
String s = editable.toString();
int start = mEditText.getSelectionStart();
int end = mEditText.getSelectionEnd();
if (start == end && start < s.length() && start > 1) {
s = s.substring(0, start - 1) + s.substring(start);
} else {
s = s.substring(0, s.length() - 1);
}
mEditText.setText(s);
mEditText.setSelection(mEditText.getText().length());
// Toast.makeText(RatingActivity.this, "max line set to MAX_LINES", Toast.LENGTH_SHORT).show();
}
This piece of code works for me to set the EditText max lines limit to MAX_LINES.