TextWatcher 在 EditText 中输入返回键时会运行多次



我有一个带有TextWatcher的EditText。


场景 1:

编辑包含">abcd"的文本

如果我按回车键或输入换行符

1(在角色之前,TextWatcher开火3次。

2(在角色之间,TextWatcher开火4次。

3(在字符末尾,TextWatcher发射1次。


场景 2:

编辑包含">1234"的文本

如果我按回车键或输入换行符

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 条件中的代码只执行一次

这是因为数字被计为单个值,即数字 1 或 12 "十二"而不是 1,2。相反,当您输入单词"字符串"时,它们被分成字符,并且整个字符串中的字符总数在 textWatcher 重载方法的 count 参数中返回。

例如,如果您输入 123,它将被解释为一百二十三的单个值。因此,计数返回为 1。当您输入hello时,它被分成单独的字符,即"h","e","l","l","o",总共计为5个字符。因此,总计数返回为 5。

希望这个解释有所帮助。

最新更新