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

Android EditText 即時監聽輸入並根據內容更新 TextView:TextWatcher 完整範例

     編輯:程式設計疑難解答

核心元件:TextWatcher

addTextChangedListener 提供三個回調,典型場景用 afterTextChanged 取得最終內容。

完整實作


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) {}
    
    @Override
    public void afterTextChanged(Editable s) {
        String input = s.toString().trim();
        if ("1".equals(input)) {
            textView.setText("11");
        } else if ("2".equals(input)) {
            textView.setText("222");
        } else {
            textView.setText("3333 " + input);
        }
    }
});

關鍵細節

  1. 字串比較用 equals:== 比較記憶體位址,"1".equals(input) 避免空指標且語義正確。
  2. 避免死迴圈:在 afterTextChanged 中修改同一 EditText 會再次觸發監聽。若需修改輸入框本身,改用 onTextChanged 並判斷 count != after,或移除/重加監聽器。
  3. 效能:頻繁觸發時考慮 Debounce(如 RxJava debounce(300, TimeUnit.MILLISECONDS))減少 UI 更新次數。
  4. InputFilter 替代:若僅需限制輸入格式(長度、字元集),實作 InputFilter 設 setFilters 更輕量。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved