最近工作這塊好折騰,雖然用正則可以解決,但是還是翻閱了下Android提供的方式。
下面是我總結和在網上看到的,希望對大家有幫助。
如何設置EditText,使得只能輸入數字或者某些字母呢?
一、設置EditText,只輸入數字:
方法1:直接生成DigitsKeyListener對象就可以了。
et_1.setKeyListener(new DigitsKeyListener(false,true));
方法2:在EditText中設置屬性,android:numeric="integer"即只能輸入整數,如下
android:numeric="integer"
方法3:新建一個char[],在里面添加允許輸入的字符。如下
1 etCoustom.setKeyListener(new NumberKeyListener() { 2 @Override 3 protected char[] getAcceptedChars() { 4 char[] numberChars={'1','2','3','4','5','6','7','8','9','0'}; 5 return numberChars; 6 } 7 8 @Override 9 public int getInputType() { 10 return android.text.InputType.TYPE_CLASS_PHONE; 11 } 12 });
二、設置EditText只能輸入某些字母,如下面設置edtitext只能輸入A—N,a—n這些字母。方法如下:
editText.setKeyListener(new NumberKeyListener(){ protected char[] getAcceptedChars() { char[] numberChars[]={'a,'b','c','d','e','f','A','B','C','D'}; return numberChars; } });
另外:設置小數等各種類型的東西可以參考我的另外的隨筆:【android EditText中的inputType】
下面文字摘自網上:
很多網友可能在開發Android時發現EditText有時候需要限制用戶輸入的內容,通常我們可以使用正則表達式直接限制,但是Android
已經為我們准備好了EditText的輸入類型,這樣的比正則要有以下幾點優勢:
1. 開發更簡單,執行速度高效。 2.
輸入法默認會根據情況變動,比如說設置為numeric后輸入法會自動僅顯示數字,不會出現Qwerty中的字母。
下面我們通過EditText的layout
xml文件中的相關屬性來實現:
1. 密碼框屬性 android:password="true"
這條可以讓EditText顯示的內容自動為 星號,輸入時內容會在1秒內變成*字樣。
2. 純數字 android:numeric="true"
這條可以讓輸入法自動變為數字輸入鍵盤,同時僅允許0-9的數字輸入
3. 僅允許 android:capitalize="cwj1987"
這樣僅允許接受輸入cwj1987,一般用於密碼驗證
下面是一些擴展的風格屬性
android:editable="false"
設置EditText不可編輯
android:singleLine="true"
強制輸入的內容在單行
android:ellipsize="end"
自動隱藏尾部溢出數據,一般用於文字內容過長一行無法全部顯示時。
