Android TextWatcher內容監聽死循環案例詳解

Android TextWatcher內容監聽死循環

TextWatcher如何避免在afterTextChanged中調用setText後導致死循環,今天在用TextView時,添加瞭addTextChangedListener方法監聽內容改變,在afterTextChanged方法中又執行瞭setText方法,結果造成afterTextChanged方法再次調用,然後setText,因此造成瞭死循環的問題。列出此問題,以備後忘。

先貼Google文檔原文說明:

/** * This method is called to notify you that, somewhere within * <code>s</code>, the text has been changed. * It is legitimate to make further changes to <code>s</code> from * this callback, but be careful not to get yourself into an infinite * loop, because any changes you make will cause this method to be * called again recursively. * (You are not told where the change took place because other * afterTextChanged() methods may already have made other changes * and invalidated the offsets. But if you need to know here, * you can use {@link Spannable#setSpan} in {@link #onTextChanged} * to mark your place and then look up from here where the span * ended up. */public void afterTextChanged(Editable s);

根據文檔說明意思就是調用setText之前暫時去掉此監聽器, 然後再恢復添加自身即可.

如下:

xxxEdit.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) {
xxxEdit.removeTextChangedListener(this);
xxxEdit.setText("新取值");
xxxEdit.addTextChangedListener(this);
}
});