您好,登錄后才能下訂單哦!
要防止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ù)的部分將被自動刪除。
免責(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)容。