如何更改 DataChange 上的 TextView 文本而不回调 TextWatcher 侦听器
考虑一下:
TextView textView = new TextView(context);
textView.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
s.append("A");
}
});
如果我们向 TextView
添加一个 TextWatcher
,并且我想向这个 TextView
附加一个字母,每次用户写一封信时在其中,但这会不断调用 TextWatcher
监听器,从而导致 StackOverFlow 错误
,那么如何在不再次调用 TextWatcher
监听器的情况下附加文本?
Consider:
TextView textView = new TextView(context);
textView.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
s.append("A");
}
});
If we add a TextWatcher
to a TextView
, and I want to append a letter to this TextView
, every time the user writes a letter in it, but this keeps calling the TextWatcher
Listener, so on to StackOverFlow error
, so how can I append text without calling the TextWatcher
Listener again?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这很简单:
It's easy:
另一种避免堆栈溢出的方法:
Another way to avoid a stack overflow:
afterTextChanged 的文档说:
调用此方法是为了通知您,在 s 内的某个位置,文本已更改。从此回调中对 s 进行进一步更改是合法的,但要小心不要让自己陷入无限循环,因为您所做的任何更改都会导致再次递归调用此方法。 (不会告诉您更改发生在哪里,因为其他 afterTextChanged() 方法可能已经进行了其他更改并使偏移量无效。但是如果您需要知道这里,您可以使用 setSpan(Object, int, int, int ) 在
onTextChanged(CharSequence, int, int, int)
中标记您的位置,然后从此处查找跨度结束的位置。因此,对于每个
s.append("A")
您再次调用 afterTextChanged()
等等。The documentation of afterTextChanged says:
This method is called to notify you that, somewhere within s, the text has been changed. It is legitimate to make further changes to s 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
setSpan(Object, int, int, int)
inonTextChanged(CharSequence, int, int, int)
to mark your place and then look up from here where the span ended up.So, with every
s.append("A")
youcall afterTextChanged()
again and so on.一些伪代码,这样你就可以做到这一点:
只需改变焦点......
所以像这样:
Some pseudocode so you can do this:
Just change the focus...
So like this:
科特林版本
Kotlin Version