我找到了解决方案,但可能无法满足所有需求。
早些时候,当TextWatcher 被多次触发并且其中的代码也被多次执行时,我和
editText.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
Log.e(TAG, "111 text =---------------" + charSequence);
}
public void onTextChanged(CharSequence charSequence, int start, int before, int count){
Log.e(TAG, "222 text =---------------" + charSequence);
}
public void afterTextChanged(Editable editable) {
Log.e(TAG, "333 text ---------------" + editable);
}
});
现在,根据我的要求,我找到了解决方案,我同意了
editText.addTextChangedListener(new TextWatcher() {
String initialText = "";
private boolean ignore = true;
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
if ( initialText.length() < charSequence.length() ){
initialText = charSequence.toString();
Log.e(TAG, "111 text ---------------" + charSequence);
}
}
public void onTextChanged(CharSequence charSequence, int start, int before, int count){
if( initialText.length() < charSequence.length() ) {
initialText="";
ignore=false;
Log.e(TAG, "222 text ---------------" + charSequence);
}
}
public void afterTextChanged(Editable editable) {
if(!ignore) {
ignore = true;
Log.e(TAG, "333 text ---------------" + editable);
}
}
});
现在TextWatcher 也多次触发,但对于我在问题中提到的所有场景,if 条件仅执行一次中的代码。