本文實例講述了Android編程中EditText限制文字輸入的方法。分享給大家供大家參考,具體如下:
Android的編輯框控件EditText在平常編程時會經(jīng)常用到,有時候會對編輯框增加某些限制,如限制只能輸入數(shù)字,最大輸入的文字個數(shù),不能輸入一些非法字符等,這些需求有些可以使用android控件屬性直接寫在布局xml文件里,比如android:numeric="integer"(只允許輸入數(shù)字);
對于一些需求,如非法字符限制(例如不允許輸入#號,如果輸入了#給出錯誤提示),做成動態(tài)判斷更方便一些,而且容易擴展;
在Android里使用TextWatcher接口可以很方便的對EditText進行監(jiān)聽;TextWatcher中有3個函數(shù)需要重載:
1
2
3
|
public void beforeTextChanged(CharSequence s, int start, int count, int after); public void onTextChanged(CharSequence s, int start, int before, int count); public void afterTextChanged(Editable s); |
從函數(shù)名就可以知道其意思,每當敲擊鍵盤編輯框的文字改變時,上面的三個函數(shù)都會執(zhí)行,beforeTextChanged可以給出變化之前的內(nèi)容,onTextChanged和afterTextChanged給出追加上新的字符之后的文本;
所以對字符的限制判斷可以在afterTextChanged函數(shù)中進行,如果檢查到新追加的字符為認定的非法字符,則在這里將其delete掉,那么他就不會顯示在編輯框里了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
private final TextWatcher mTextWatcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } public void afterTextChanged(Editable s) { if (s.length() > 0 ) { int pos = s.length() - 1 ; char c = s.charAt(pos); if (c == '#' ) { //這里限制在字串最后追加# s.delete(pos,pos+ 1 ); Toast.makeText(MyActivity. this , "Error letter." ,Toast.LENGTH_SHORT).show(); } } } }; |
注冊監(jiān)聽:
1
2
|
EditText mEditor = (EditText)findViewById(R.id.editor_input); mEditor.addTextChangedListener(mTextWatcher); |
希望本文所述對大家Android程序設(shè)計有所幫助。