TextWatcher如何避免在afterTextChanged中調用setText后導致死循環(huán),今天在用TextView時,添加了addTextChangedListener方法監(jiān)聽內容改變,在afterTextChanged方法中又執(zhí)行了setText方法,結果造成afterTextChanged方法再次調用,然后setText,因此造成了死循環(huán)的問題。列出此問題,以備后忘。
先貼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);
根據(jù)文檔說明意思就是調用setText之前暫時去掉此監(jiān)聽器, 然后再恢復添加自身即可.
如下:
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); } });