歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中對文本框裡的值進行過濾

Android中對文本框裡的值進行過濾

日期:2017/3/1 10:40:58   编辑:Linux編程

1。在網上看到對文本框裡的值進行限制,無非都是文本框裡的值,只能輸入數字,或者文本和數字都可以輸入,但卻沒有讓數字,文本,軟鍵盤上的空格鍵等都同時限制的屬性。如: Android:inputType="text"這個就可以實現文本和數字都可以輸入;android:numeric="integer"這個就可以實現文本裡只能輸入數字

2。但是你在文本框裡輸入空格呢,上面的屬性就不起作用了。下面的代碼就可以解決這個問題,即便你輸入空格,文本框也不會有任何的操作:

InputFilter[] input = new InputFilter[1];
input[0] = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
int permit = 3;
if (0 < dend) {
if (dest.charAt(0) <= 57)
permit = 1;
else
permit = 2;
}
String str = new String();
for (int t = start; t < end; t++) {
char ch = source.charAt(t);
if ((permit & 1) != 0) {
if (ch >= 48 && ch <= 57) {
str += ch;
permit = 1;
}
}
if ((permit & 2) != 0) {
ch &= ~0x20;
if (ch >= 65 && ch <= 90) {
str += ch;
permit = 2;
}
}
}
return str;
}
};
edittext.setFilters(input);

Copyright © Linux教程網 All Rights Reserved