androidtextviewtextwatcher

How to change TextView text on DataChange without calling back a TextWatcher listener


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?


Solution

  • 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) in onTextChanged(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") you call afterTextChanged() again and so on.