EditText限制輸入型別為英數字並限制長度
阿新 • • 發佈:2019-01-23
方法一:
EditText標籤下增加以下屬性:
android:maxLength="18"
android:digits="1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
方法二:
通過TextWatcher實現,更加靈活。
首先,自定義一個TextWatcher:
然後在EditText的物件上設定該TextWatcher即可:public static class IDNumberTextWatcher implements android.text.TextWatcher { /** * This method is called to notify you that, within <code>s</code>, * the <code>count</code> characters beginning at <code>start</code> * are about to be replaced by new text with length <code>after</code>. * It is an error to attempt to make changes to <code>s</code> from * this callback. */ @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } /** * This method is called to notify you that, within <code>s</code>, * the <code>count</code> characters beginning at <code>start</code> * have just replaced old text that had length <code>before</code>. * It is an error to attempt to make changes to <code>s</code> from * this callback. */ @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } /** * This method is called to notify you that, somewhere within * <code>s</code>, the text has been changed. * It is legitimate to make further changes to <code>s</code> from * this callback, but be careful not to get yourself into an infinite * loop, because any changes you make will cause this method to be * called again recursively. * (You are not told where the change took place because other * afterTextChanged() methods may already have made other changes * and invalidated the offsets. But if you need to know here, * you can use {@link Spannable#setSpan} in {@link #onTextChanged} * to mark your place and then look up from here where the span * ended up. */ @Override public void afterTextChanged(Editable s) { String temp = s.toString(); Log.d(TAG, "temp=" + temp); if (!TextUtils.isEmpty(temp)) { if (temp.length() <= 18) { String tem = temp.substring(temp.length() - 1, temp.length()); char[] temC = tem.toCharArray(); int mid = temC[0]; // Number if(mid>=48&&mid<=57){ return; } // Upper case if(mid>=65&&mid<=90){ return; } // Lower case if(mid>=97&&mid<=122){ return; } } else { Log.d(TAG, "current input length is over 18"); } s.delete(temp.length()-1, temp.length()); } else { Log.d(TAG, "current input is null"); } } }
idNumEt.addTextChangedListener(new IDNumberTextWatcher());