How can I change the EditText text without triggering the Text Watcher?
Short answer
You can check which View currently has the focus to distinguish between user and program triggered events.
EditText myEditText = (EditText) findViewById(R.id.myEditText);
myEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (myEditText.hasFocus()) {
// is only executed if the EditText was directly changed by the user
}
}
//...
});
Long answer
As an addition to the short answer:
In case myEditText
already has the focus when you programmatically change the text you should call clearFocus()
, then you call setText(...)
and after you you re-request the focus. It would be a good idea to put that in a utility function:
void updateText(EditText editText, String text) {
boolean focussed = editText.hasFocus();
if (focussed) {
editText.clearFocus();
}
editText.setText(text);
if (focussed) {
editText.requestFocus();
}
}
For Kotlin:
Since Kotlin supports extension functions your utility function could look like this:
fun EditText.updateText(text: String) {
val focussed = hasFocus()
if (focussed) {
clearFocus()
}
setText(text)
if (focussed) {
requestFocus()
}
}
You could unregister the watcher, and then re-register it.
Alternatively, you could set a flag so that your watcher knows when you have just changed the text yourself (and therefore should ignore it).
Java:
public class MyTextWatcher implements TextWatcher {
private EditText editText;
// Pass the EditText instance to TextWatcher by constructor
public MyTextWatcher(EditText editText) {
this.editText = editText;
}
@Override
public void afterTextChanged(Editable e) {
// Unregister self before update
editText.removeTextChangedListener(this);
// The trick to update text smoothly.
e.replace(0, e.length(), e.toString());
// Re-register self after update
editText.addTextChangedListener(this);
}
...
}
Kotlin:
class MyTextWatcher(private val editText: EditText) : TextWatcher {
override fun afterTextChanged(e: Editable) {
editText.removeTextChangedListener(this)
e.replace(0, e.length, e.toString())
editText.addTextChangedListener(this)
}
...
}
Usage:
et_text.addTextChangedListener(new MyTextWatcher(et_text));
You may feel a little bit lag when entering text rapidly if you are using editText.setText() instead of editable.replace().