近期的項目上須要限制EditText輸入字符的類型,就把能夠實現這個功能的方法整理了一下:
1、第一種方式是通過EditText的inputType來實現,能夠通過xml或者java文件來設置。假如我要設置為顯示password的形式,能夠像以下這樣設置:
在xml中。 android:inputType="textPassword"
在java文件里,能夠用 myEditText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
當然,還有很多其它的其它屬性用來進行輸入設置。
2、另外一種是通過android:digits 屬性來設置,這樣的方式能夠指出要顯示的字符。比方我要限制僅僅顯示數字,能夠這樣:
android:digits="0123456789"
假設要顯示的內容比較多,就比較麻煩了,將要顯示的內容依次寫在里面。
3、通過正則表達式來推斷。以下的樣例僅僅同意顯示字母、數字和漢字。
public static String stringFilter(String str)throws PatternSyntaxException{
然后須要在TextWatcher的onTextChanged()中調用這個函數,
@Override
4、通過InputFilter來實現。
實現InputFilter過濾器,須要覆蓋一個叫filter的方法。
public abstract CharSequence filter (
CharSequence source, //輸入的文字
int start, //開始位置
int end, //結束位置
Spanned dest, //當前顯示的內容
int dstart, //當前開始位置
int dend //當前結束位置
);
以下的實現使得EditText僅僅接收字符(數字、字母和漢字)和“-”“_”,Character.isLetterOrDigit會把中文也當做Letter。
editText.setFilters(new InputFilter[] {
} });
另外使用InputFilter還能限制輸入的字符個數,如
EditText tv =newEditText(this);
int maxLength =10;
InputFilter[] fArray =new InputFilter[1];
fArray[0]=new InputFilter.LengthFilter(maxLength);
tv.setFilters(fArray);
上面的代碼能夠限制輸入的字符數最大為10。