使用setFilters时,无法正确应用EditText maxLength属性 [英] EditText maxLength property not applied properly when setFilters is used
问题描述
当我在EditText
上使用setFilter
方法来处理特殊字符时,maxLength
属性无法正常工作.我的代码在下面.
When I use setFilter
method on an EditText
to handle special characters, maxLength
property is not working as expected. My code is below.
editName = (EditText)findViewById(R.id.rna_editTextName);
editName.setFilters(new InputFilter[]{getFilteredChars()});
//Below method returns filtered characters.
public InputFilter getFilteredChars()
{
InputFilter filter = new InputFilter()
{
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (end > start) {
char[] acceptedChars = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ' ,'.', '\''};
for (int index = start; index < end; index++) {
if (!new String(acceptedChars).contains(String.valueOf(source.charAt(index)))) {
return "";
}
}
}
return null;
}
};
return filter;
}
推荐答案
这是因为maxLength
属性在EditText
上设置了InputFilter
.通过调用EditText.setFilters(new InputFilter[] {<YOUR_FILTER>})
,您将覆盖所有现有的InputFilter,包括由maxLength
使用的InputFilter.
This is because the maxLength
property sets an InputFilter
on your EditText
. By calling EditText.setFilters(new InputFilter[] {<YOUR_FILTER>})
you are overriding all existing InputFilters including the one used by maxLength
.
要解决此问题,请复制EditText.getFilters()
返回的数组并将其添加到其中:
To fix this, copy the array returned by EditText.getFilters()
and add your own to it:
InputFilter[] editFilters = edit.getFilters();
InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
newFilters[editFilters.length] = <YOUR_FILTER>;
edit.setFilters(newFilters);
这篇关于使用setFilters时,无法正确应用EditText maxLength属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!