I want to make the EditText
with max lines of 2 and max length of 20. If the EditText
length is more than 10, it should automatically go to a new line so the user don't need to press Enter. Can someone help me with this requirement?
问题:
回答1:
ADD this to your EditText xml code
android:inputType="textMultiLine"
This will automatically moves your text to next line while entering data.
回答2:
It should exist a most elegant way but this solution might help you as a clue to achieve what you want. First of all, you will need to set your EditText
values as below:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text|textMultiLine|textCapSentences"
android:maxLength="21"
android:gravity="left"
android:maxLines="2" />
You must to set the maxLength
attribute to 21
because the enter char (new line) will take one char in the edittext, then the user will only can write 19
chars instead of 20
.
Then, you should use a TextWatcher
with a boolean
(used if the user removes his previous chars), and this should be as follows:
// init global boolean
private boolean isReached = false;
// in onCreate method
edittext.addTextChangedListener(new TextWatcher(){
@Override
public void afterTextChanged(Editable s) {
// if edittext has 10chars & this is not called yet, add new line
if(textEd.getText().length() == 10 && !isReached) {
textEd.append("\n");
isReached = true;
}
// if edittext has less than 10chars & boolean has changed, reset
if(textEd.getText().length() < 10 && isReached) isReached = false;
}
});
Note: However, you should be careful with this code. Indeed, the user can still pressed the Key Enter
and then, add new lines. Maybe these answers might help you to handle it and keep the user only "on your road": Prevent enter key on EditText but still show the text as multi-line
回答3:
For the EditText to display 2 lines. You can write like this:
android:maxLength="20"
android:maxLines="2"
android:singleLine="false"
android:layout_width="Your Choice"
回答4:
For the lines, do something like:
<EditText
android:inputType="textMultiLine" <!-- Multiline input -->
android:lines="2" <!-- Total Lines prior display -->
android:minLines="1" <!-- Minimum lines -->
android:gravity="top|left" <!-- Cursor Position -->
android:maxLines="2" <!-- Maximum Lines -->
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
you could also play with this parameter (Does NOT work for Android <= 3.0):
android:singleLine="false"
And for the number of characters, do something like:
EditText et= (EditText) findViewById(R.id.editText1);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(20); //Filter to 20 characters
et.setFilters(filters);
or, use this other parameter,
android:maxLength="20"
in the xml