自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Android開發(fā)中限制EditText輸入字符的幾種實(shí)用方法

移動開發(fā) Android
TextWatcher 可以用于監(jiān)聽文本變化,并在輸入時實(shí)施限制。例如檢查輸入是否包含某些特定字符,并刪掉不是字母或數(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)大和靈活的文本處理能力。

責(zé)任編輯:武曉燕 來源: 沐雨花飛蝶
相關(guān)推薦

2011-02-22 11:11:33

EditTextAndroid

2024-06-03 08:26:34

Android開發(fā)監(jiān)聽器

2017-03-12 19:51:38

js實(shí)用跨域

2020-10-16 18:35:53

JavaScript字符串正則表達(dá)式

2018-08-09 20:47:41

2024-03-26 07:46:13

El-input正則表達(dá)式正則整理

2013-07-16 14:47:18

Android EdiEditText不彈出Android開發(fā)

2020-09-24 14:06:19

Vue

2020-06-17 09:15:57

MySQLSQL數(shù)據(jù)庫

2009-12-16 13:48:06

Ruby Web開發(fā)框

2013-01-08 13:46:58

Android開發(fā)ViewStub布局

2013-06-25 11:06:07

Android開發(fā)顏色定義方法

2021-10-13 17:58:57

模型人工智能函數(shù)

2009-08-06 17:24:08

C#字符串

2013-06-27 17:26:01

AndroidEditText

2021-03-08 09:32:04

Python文件命令

2024-05-23 08:24:11

Android進(jìn)程開發(fā)

2024-04-28 14:49:31

2023-06-30 17:52:00

WebDjagno框架

2010-01-25 15:57:34

Android保存數(shù)據(jù)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號