Android開發(fā)中限制EditText輸入字符的幾種實(shí)用方法
在 Android 開發(fā)中,經(jīng)常需要限制 EditText 的輸入字符,以下是幾種不同的實(shí)現(xiàn)方法。
使用 InputFilter
通過實(shí)現(xiàn) InputFilter 接口來限制輸入。例如限制輸入長度為 10。
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(10);
editText.setFilters(filters);正則判斷是否輸入的是中文:
editText.setFilters(new InputFilter[]{
    new InputFilter() {
        @Override
        public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
            String regex = "^[\u4E00-\u9FA5]+$";
            boolean isChinese = Pattern.matches(regex, charSequence.toString());
            if (!Character.isLetterOrDigit(charSequence.charAt(i)) || isChinese) {
                return "";
            }
            return null;
        }
    }
});使用 TextWatcher
TextWatcher 可以用于監(jiān)聽文本變化,并在輸入時實(shí)施限制。例如檢查輸入是否包含某些特定字符,并刪掉不是字母或數(shù)字的字符。
editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        
    }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String editable = evPwd.getText().toString();
        String regEx = "[^a-zA-Z0-9]";  //只能輸入字母或數(shù)字
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(editable);
        String str = m.replaceAll("").trim();    //刪掉不是字母或數(shù)字的字符
        if(!editable.equals(str)){
            evPwd.setText(str);  //設(shè)置EditText的字符
            evPwd.setSelection(str.length()); //因?yàn)閯h除了字符,要重寫設(shè)置新的光標(biāo)所在位置
        }
    }
    @Override
    public void afterTextChanged(Editable s) {
        
    }
});使用 XML 屬性
在 XML 中使用屬性來限制 EditText 輸入字符,如 android:inputType 和 android:digits。
只能輸入數(shù)字:
<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:digits="0123456789" />只能輸入0~9 小寫a~z:
<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:digits="0123456789abcdefghijklmnopqrstuvwxyz" />自定義 EditText
對于更復(fù)雜的需求,可以通過自定義 EditText 控件實(shí)現(xiàn)輸入限制。
public class LimitEditText extends EditText {
    public LimitEditText(Context context) {
        super(context);
    }
    public LimitEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public LimitEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new InnerInputConnecttion(super.onCreateInputConnection(outAttrs), false);
    }
    class InnerInputConnecttion extends InputConnectionWrapper implements InputConnection {
        public mInputConnecttion(InputConnection target, boolean mutable) {
            super(target, mutable);
        }
        /**
         * 對輸入的內(nèi)容進(jìn)行攔截
         *
         * @param text
         * @param newCursorPosition
         * @return
         */
        @Override
        public boolean commitText(CharSequence text, int newCursorPosition) {
            // 只能輸入字母或者數(shù)字
            if (!Character.isLetterOrDigit(charSequence.charAt(i)) || isChinese)  {
                return false;
            }
            return super.commitText(text, newCursorPosition);
        }
        @Override
        public boolean sendKeyEvent(KeyEvent event) {
            return super.sendKeyEvent(event);
        }
        @Override
        public boolean setSelection(int start, int end) {
            return super.setSelection(start, end);
        }
    }
}注意事項(xiàng)
- 當(dāng)使用 TextWatcher 時,要小心不要創(chuàng)建無限循環(huán)。例如,如果在 onTextChanged 方法中直接修改 EditText 的文本,并且沒有適當(dāng)?shù)臋z查來防止不必要的修改,那么可能會導(dǎo)致無限循環(huán)。
 - 對于復(fù)雜的輸入限制,考慮使用正則表達(dá)式來匹配和過濾文本??梢蕴峁└鼜?qiáng)大和靈活的文本處理能力。
 















 
 
 









 
 
 
 