简体   繁体   English

Android:绑定到 EditText 时触发 TextWatcher.onTextChanged

[英]Android: TextWatcher.onTextChanged fires when binding to EditText

When I set a TextWatcher to a EditText like so:当我将TextWatcher设置为EditText如下所示:

editText1.addTextChangedListener(watcher);

Interface methods onTextChanged , afterTextChanged and beforeTextChanged are fired, no matter if the EditText contains text or not.无论EditText包含文本, afterTextChanged触发onTextChangedafterTextChangedbeforeTextChanged接口方法。

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 .setText()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    
    ...

Those methods should not fire when you just call addTextChangedListener(TextWatcher) .当您只调用addTextChangedListener(TextWatcher)时,不应触发这些方法。 Likely you are just calling setText() or otherwise modifying the text programatically.可能您只是在调用setText()或以其他方式以编程方式修改文本。


This is the source code of android.widget.TextView.addTextChangedListener :这是android.widget.TextView.addTextChangedListener的源代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM