How can I avoid that a code line like:
((EditText) findViewById(R.id.MyEditText)).setText("Hello");
Will cause an event here:
((EditText) findViewById(R.id.MyEditText)).addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// HERE
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
I want to know if there is any way to inhibit the execution of onTextChanged as I noticed in the case of selecting a AutoCompleteTextView's dropdown result (no onTextChanged is executed!).
I'm not seeking for workarounds like "if hello do nothing"...
Only two ways I can see
As the first way is a unwanted workaround for you I am a afraid you have work around with the second way.
I don't think there is an easy way to disable the listener, but you can get around it by either:
TextWatcher
before you set the text, and adding it back after.boolean
flag before you set the text, which tells theTextWatcher
to ignore it.E.g.
And in your
TextWatcher
:It's a little hacky, but it should work :)
The Source for AutoCompleteTextView shows that they set a boolean to say the text is being replaced by the block completion
This is as good a way as any to achieve what you want to do. The TextWatcher then checks to to see if the setText has come via a completion and returns out of the method
Adding and removing the TextWatcher will be more time consuming for the application
You can check which View has the focus currently to distinguish between user and program triggered events.
An alternative way to achieve this would be to use
setOnKeyListener
.This will only trigger when the user presses a key rather than whenever the EditText is changed by the user OR programmatically.
Alternatively you can simply use
mEditText.hasFocus()
to distinguish between Text that human-changed or program-changed, this works fine for me:Hope this helps!