user1324936
user1324936

Reputation: 2187

Android: TextWatcher.onTextChanged fires when binding to EditText

When I set a TextWatcher to a EditText like so:

editText1.addTextChangedListener(watcher);

Interface methods onTextChanged, afterTextChanged and beforeTextChanged are fired, no matter if the EditText contains text or not.

I assumed that these methods are called only after a text change after binding. Can I prevent this behaviour? Have I made a logical error that is resulting in this behaviour?

Thanks

Edit:

I setText() before addTextChangedListener.

call stack:

DalvikVM[localhost:8600]    
Thread [<1> main] (Suspended)   
    <VM does not provide monitor information>   
    EditText(TextView).sendOnTextChanged(CharSequence, int, int, int) line: 7875    
    EditText(TextView).setText(CharSequence, TextView$BufferType, boolean, int) line: 3488  
    EditText(TextView).setText(CharSequence, TextView$BufferType) line: 3341    
    EditText.setText(CharSequence, TextView$BufferType) line: 90    
    EditText(TextView).setText(CharSequence) line: 3316 
    EditText(TextView).onRestoreInstanceState(Parcelable) line: 3216    
    EditText(View).dispatchRestoreInstanceState(SparseArray) line: 10079    
    ...

Upvotes: 0

Views: 4050

Answers (1)

Oleg Vaskevich
Oleg Vaskevich

Reputation: 12672

Those methods should not fire when you just call addTextChangedListener(TextWatcher). Likely you are just calling setText() or otherwise modifying the text programatically.


This is the source code of android.widget.TextView.addTextChangedListener:

public void addTextChangedListener(TextWatcher watcher) {
    if (mListeners == null) {
        mListeners = new ArrayList<TextWatcher>();
    }
    mListeners.add(watcher);
}

Upvotes: 2

Related Questions