Limit text length of EditText in Android

2019-01-01 01:47发布

What's the best way to limit the text length of an EditText in Android?

Is there a way to do this via xml?

16条回答
看风景的人
2楼-- · 2019-01-01 02:20

Xml

android:maxLength="10"

Java:

InputFilter[] editFilters = editText.getFilters();
InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
newFilters[editFilters.length] = new InputFilter.LengthFilter(maxLength);
editText.setFilters(newFilters);

Kotlin:

editText.filters += InputFilter.LengthFilter(maxLength)
查看更多
长期被迫恋爱
3楼-- · 2019-01-01 02:22

A note to people who are already using a custom input filter and also want to limit the max length:

When you assign input filters in code all previously set input filters are cleared, including one set with android:maxLength. I found this out when attempting to use a custom input filter to prevent the use of some characters that we don't allow in a password field. After setting that filter with setFilters the maxLength was no longer observed. The solution was to set maxLength and my custom filter together programmatically. Something like this:

myEditText.setFilters(new InputFilter[] {
        new PasswordCharFilter(), new InputFilter.LengthFilter(20)
});
查看更多
后来的你喜欢了谁
4楼-- · 2019-01-01 02:22

This works fine...

android:maxLength="10"

this will accept only 10 characters.

查看更多
后来的你喜欢了谁
5楼-- · 2019-01-01 02:23

Another way you can achieve this is by adding the following definition to the XML file:

<EditText
    android:id="@+id/input"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:maxLength="6"
    android:hint="@string/hint_gov"
    android:layout_weight="1"/>

This will limit the maximum length of the EditText widget to 6 characters.

查看更多
登录 后发表回答