在Android中限制EditText文本长度的最佳方法是什么?

有没有通过xml实现这一点的方法?


当前回答

对于已经使用自定义输入筛选器并希望限制最大长度的用户,请注意:

当您在代码中分配输入过滤器时,所有先前设置的输入过滤器都将被清除,包括一个使用android:maxLength设置的过滤器。我在尝试使用自定义输入筛选器以防止在密码字段中使用某些不允许的字符时发现了这一点。使用setFilters设置过滤器后,不再观察到maxLength。解决方案是以编程方式将maxLength和自定义过滤器设置在一起。类似于:

myEditText.setFilters(new InputFilter[] {
        new PasswordCharFilter(), new InputFilter.LengthFilter(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);

科特林:

editText.filters += InputFilter.LengthFilter(maxLength)

您可以在EditText中使用android:maxLength=“10”。(此处限制为最多10个字符)

EditText editText = new EditText(this);
int maxLength = 3;    
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});

文档

实例

android:maxLength="10"

以编程方式为Java尝试以下操作:

myEditText(new InputFilter[] {new InputFilter.LengthFilter(CUSTOM_MAX_LEN)});