华域联盟 Andriod Android TextWatcher内容监听死循环案例详解

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);
}
});

到此这篇关于Android TextWatcher内容监听死循环案例详解的文章就介绍到这了,更多相关Android TextWatcher内容监听死循环内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

本文由 华域联盟 原创撰写:华域联盟 » Android TextWatcher内容监听死循环案例详解

转载请保留出处和原文链接:https://www.cnhackhy.com/109650.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们