Events Of Textwatcher Are Being Called Twice
On my application I put TextWatcher on EditText. When I change the text of the EditText, the events of TextWatcher are being called twice. I am using emulator for running the app.
Solution 1:
How does your code looks like? that is the normal behaviour of TextWatcher. Example:
myInput.addTextChangedListener(newTextWatcher() {
booleanmToggle=false;
publicvoidonTextChanged(CharSequence cs, int s, int b, int c) {}
publicvoidafterTextChanged(Editable editable) {
if (mToggle) {
Toast.makeText(getBaseContext(), "HIT KEY",Toast.LENGTH_LONG).show();
}
mToggle = !mToggle;
}
publicvoidbeforeTextChanged(CharSequence cs, int i, int j, int k) {}
});
Solution 2:
My problem was I added the textWatcher twice mEditText.addTextChangedListener(mTextWatcher)
, which leads to calling its callbacks twice!
I had added the textWatcher once in onCreate()
and once in onStart()
.
I should only add in onStart
and remove in onStop()
.
Solution 3:
In case you call editText.setText("string")
inside your TextWatcher
listener (for example in afterTextChanged
method), TextWatcher
will detect a new text change, that might end up by calling again setText
and create a loop.
An alternative to editText.setText("string")
could be:
editText.getText().clear();
editText.append("string");
which will not evoke a new detection by the TextWatcher
listener.
Post a Comment for "Events Of Textwatcher Are Being Called Twice"