Is there a way of specifying the maximum numbers of lines for an EditText
? By that I mean all the lines of text, not only the visible ones (as the android:maxLines
attribute is described). The lines number must not be 1, so android:singleLine
is not an option.
<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 you have the attribute "inputType" set. It doesn't work without this line.
android:inputType="text"
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class EditTextLinesLimiter implements TextWatcher {
private EditText editText;
private int maxLines;
private String lastValue = "";
public EditTextLinesLimiter(EditText editText, int maxLines) {
this.editText = editText;
this.maxLines = maxLines;
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
lastValue = charSequence.toString();
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (editText.getLineCount() > maxLines) {
int selectionStart = editText.getSelectionStart() - 1;
editText.setText(lastValue);
if (selectionStart >= editText.length()) {
selectionStart = editText.length();
}
editText.setSelection(selectionStart);
}
}
}
And then:
editText.addTextChangedListener(new EditTextLinesLimiter(editText, 2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With