我有一个带有 TextWatcher 的 EditText。
场景 1:
包含“abcd”的EditText
如果我按回车键或输入换行符
1) 在字符之前,TextWatcher
触发 3 次。
2) 在字符之间,TextWatcher
触发 4 次。
3) 在字符末尾,TextWatcher
触发 1 次。
场景 2:
包含“1234”的EditText
如果我按回车键或输入换行符
1) 在字符之前,TextWatcher
触发 1 次。
2) 在字符之间,TextWatcher
触发 1 次。
3) 在字符末尾,TextWatcher
触发 1 次。
这是一个错误吗?
或者有什么我不明白的地方?
我希望文本观察器在所有场景中只触发一次。
我们将不胜感激任何帮助。
最佳答案
我找到了解决方案,但可能无法完美满足所有需求。
早些时候,当 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 条件中的代码只执行一次 对于我提到的所有场景在我的问题中。
关于java - TextWatcher 在 EditText 中输入返回键时运行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45296276/