用于InputFilter
控制用户输入:
EditText editText;
editText.setFilters(new InputFilter[] { new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// here you can evaluate user input if it's correct or not
}
} });
这是可能的filter
方法实现,但未经测试:
if (source.length() == 0) {
return null;//deleting, keep original editing
}
String result = "";
result.concat(dest.toString().substring(0, dstart));
result.concat(source.toString().substring(start, end));
result.concat(dest.toString().substring(dend, dest.length()));
if (result.length() > 5) {
return "";// do not allow this edit
}
boolean allowEdit = true;
char c;
if (result.length() > 0) {
c = result.charAt(0);
allowEdit &= (c >= '0' && c <= '2');
}
if (result.length() > 1) {
c = result.charAt(1);
allowEdit &= (c >= '0' && c <= '9');
}
if (result.length() > 2) {
c = result.charAt(2);
allowEdit &= (c == ':');
}
if (result.length() > 3) {
c = result.charAt(3);
allowEdit &= (c >= '0' && c <= '5');
}
if (result.length() > 4) {
c = result.charAt(4);
allowEdit &= (c >= '0' && c <= '9');
}
return allowEdit ? null : "";