【问题标题】:TextWatcher runs multiple times on entering Return Key in EditTextTextWatcher 在 EditText 中输入 Return Key 时运行多次
【发布时间】:2017-07-25 07:09:47
【问题描述】:

我有一个带有 TextWatcher 的 EditText。


场景 1:

EditText 包含“abcd

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

1) 在字符之前,TextWatcher 触发 3 次。

2) 在字符之间,TextWatcher 触发 4 次。

3) 在字符末尾,TextWatcher 触发 1 次。


场景 2:

EditText 包含“1234

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

1) 在字符之前,TextWatcher 触发 1 次。

2) 在字符之间,TextWatcher 触发 1 次。

3) 在字符末尾,TextWatcher 触发 1 次。


这是一个错误吗?

或者有什么我不明白的地方?


我希望文本观察器在所有场景中只触发一次。

我们将不胜感激。

【问题讨论】:

  • 你能发布你的文本更改监听器和文本观察器代码吗?

标签: java android android-edittext 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 条件仅执行一次中的代码。

【讨论】:

    【解决方案2】:

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

    例如,如果您输入 123,它将被解释为 123 的单个值。因此,计数返回为 1。当您输入 hello 时,它被划分为单个字符,即 'h'、'e'、'l'、'l'、'o',总计 5 个字符。因此,总计数返回为 5。

    希望这个解释有所帮助。

    【讨论】:

    • TextWatcher 中,定位是使用然后估值。文本观察器为 1234abcd 返回相同的位置。那么它是否也考虑估值?
    • 场景1中你可以看到所有的字母都是由数字组成的。那么为什么触发事件会有这样的差异呢?
    猜你喜欢
    • 2015-02-28
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多