TextWatcher如何避免在afterTextChanged中調(diào)用setText后導(dǎo)致死循環(huán)小槐,今天在用TextView時拇派,添加了addTextChangedListener方法監(jiān)聽內(nèi)容改變,在afterTextChanged方法中又執(zhí)行了setText方法凿跳,結(jié)果造成afterTextChanged方法再次調(diào)用件豌,然后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ù)文檔說明意思就是調(diào)用setText之前暫時去掉此監(jiān)聽器, 然后再恢復(fù)添加自身即可.
如下:
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);
}
});