限制Android中EditText文本长度的最佳方法是什么?
有没有办法通过xml做到这一点?
#1楼
一个注谁正在使用一个自定义的输入滤波器, 也希望限制最大长度的人:
当您在代码中分配输入过滤器时,所有先前设置的输入过滤器都会被清除,包括android:maxLength一组。 在尝试使用自定义输入过滤器以防止使用某些密码字段中不允许的字符时,我发现了这一点。 使用setFilters设置该过滤器后,不再观察到maxLength。 解决方案是通过编程将maxLength和我的自定义过滤器一起设置。 像这样:
myEditText.setFilters(new InputFilter[] {
new PasswordCharFilter(), new InputFilter.LengthFilter(20)
});
#2楼
由于goto10的观察,我将以下代码放在一起,以防止通过设置最大长度而丢失其他过滤器:
/**
* This sets the maximum length in characters of an EditText view. Since the
* max length must be done with a filter, this method gets the current
* filters. If there is already a length filter in the view, it will replace
* it, otherwise, it will add the max length filter preserving the other
*
* @param vie