首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 多 EditText 共用 TextWatcher 區分輸入框的最佳實踐

     編輯:程式設計綜合問答

現狀

Activity 實現 TextWatcher 並同時註冊到多個 EditText,在 onTextChanged 中無法直接知曉是哪個輸入框觸發。

推薦方案:為每個 EditText 分配獨立 TextWatcher 實例

TextWatcher watcher1 = 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) {
        handleInput(text1, s.toString());
    }
    @Override public void afterTextChanged(Editable s) {}
};

TextWatcher watcher2 = new TextWatcher() {
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        handleInput(text2, s.toString());
    }
    // ... 其他方法留空
};

text1.addTextChangedListener(watcher1);
text2.addTextChangedListener(watcher2);

優勢

  • 邏輯清晰,每個輸入框處理邏輯隔離。
  • 避免在共用方法中通過 View.getId() 或 Editable 實例判斷來源,減少錯誤。
  • 便於針對不同欄位應用不同驗證規則(如手機號、郵箱、密碼強度)。

進階:提取通用邏輯

若多個欄位驗證邏輯相似,可封裝工廠方法:

private TextWatcher createWatcher(final EditText target, final Validator validator) {
    return new TextWatcher() {
        @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
            validator.validate(target, s.toString());
        }
        // ...
    };
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved