Detailed Explanation of Android TextWatcher Content Monitoring Infinite Loop Case

  • 2021-12-13 17:18:13
  • OfStack

Android TextWatcher Content Listening Loop

How can TextWatcher avoid dead loop after calling setText in afterTextChanged? Today, when using TextView, addTextChangedListener method is added to monitor content changes, and setText method is executed in afterTextChanged method, resulting in afterTextChanged method being called again, and then setText, thus causing the problem of dead loop. List this problem in case you forget it later.

Post the original description of Google document first:

/** * 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);

According to the documentation, it means temporarily removing this listener before calling setText, and then resuming adding itself.

As follows:


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(" New value ");
xxxEdit.addTextChangedListener(this);
}
});


Related articles: