本文介绍了如何在不回调 TextWatcher 侦听器的情况下更改 DataChange 上的 TextView 文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

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 侦听器的情况下附加文本又来了?

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?

推荐答案

afterTextChanged 的​​文档说:

The documentation of afterTextChanged says:

调用此方法是为了通知您,在 s 内的某处,文本已更改.从这个回调中对 s 进行进一步的更改是合法的,但要小心不要让自己陷入无限循环,因为您所做的任何更改都会导致该方法再次被递归调用.(您不会被告知更改发生在何处,因为其他 afterTextChanged() 方法可能已经进行了其他更改并使偏移量无效.但是如果您需要在这里知道,您可以使用 setSpan(Object, int, int, int)onTextChanged(CharSequence, int, int, int) 中标记您的位置,然后从此处查找范围结束的位置.

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) in onTextChanged(CharSequence, int, int, int) to mark your place and then look up from here where the span ended up.

因此,对于每个 s.append("A"),您再次调用 afterTextChanged(),依此类推.

So, with every s.append("A") you call afterTextChanged() again and so on.

这篇关于如何在不回调 TextWatcher 侦听器的情况下更改 DataChange 上的 TextView 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:30