使用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 : "";
你怎麼樣限制你的EditText 5個位數? – Thommy
2 EditText的聲明每個限制,並在後處理中合併這些值。這樣你插入':'並且減輕用戶在他們的鍵盤上找到它? – jnthnjns
可能是http://developer.android.com/reference/java/util/regex/Pattern.html –