溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

EditText如何防止輸入重復(fù)內(nèi)容

發(fā)布時間:2024-08-31 11:49:52 來源:億速云 閱讀:83 作者:小樊 欄目:移動開發(fā)

要防止EditText中輸入重復(fù)內(nèi)容,可以通過編寫一個自定義EditText類并擴(kuò)展原生的EditText。在這個類中,你需要重寫onTextChanged()方法來監(jiān)聽文本變化,然后實(shí)現(xiàn)邏輯來防止重復(fù)輸入。

以下是一個示例代碼:

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatEditText;

public class NonRepeatEditText extends AppCompatEditText {
    public NonRepeatEditText(Context context) {
        super(context);
        init();
    }

    public NonRepeatEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public NonRepeatEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        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) {
                if (count > 1) { // 當(dāng)輸入內(nèi)容長度大于1時,刪除重復(fù)輸入的部分
                    String newText = s.toString().substring(start, start + count);
                    String prevText = s.toString().substring(start - before, start);
                    if (newText.equals(prevText)) {
                        Editable editable = getText();
                        editable.delete(start, start + count);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }
}

在布局文件中使用這個自定義的NonRepeatEditText:

<your.package.name.NonRepeatEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/non_repeat_edit_text"/>

這樣,當(dāng)用戶嘗試在EditText中輸入重復(fù)內(nèi)容時,重復(fù)的部分將被自動刪除。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI