How To Change TextView Text on DataChange Without Calling Back TextWatcher Listener

Mohammad Ersan picture Mohammad Ersan · Jun 15, 2011 · Viewed 13k times · Source
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 an a letter to this TextView, every time the user write a letter in it, but this keeps re-call the TextWatcher Listener, so on to StackOverFlow error, so how to append an text without re-call the TextWatcher Listener?

Answer

Andrii Chernenko picture Andrii Chernenko · Jun 9, 2013

It's easy:

@Override
public void afterTextChanged(Editable s) {
    editText.removeTextChangedListener(this);
    //Any modifications at this point will not be detected by TextWatcher,
    //so no more StackOverflowError 
    s.append("A");
    editText.addTextChangedListener(this);
}