首页 > 解决方案 > Android 7.0 的 onTextChanged TextWatcher 问题

问题描述

我的手机刚刚从 Android 6.0 更新到 7.0。更新后,我注意到我的应用程序中的一个功能无法正常工作,也就是说,EditText 不会接受输入的字符,而是会重复之前输入的字符。控制键盘设置为 CapCharacter,因此有大写字母。如果我将其设置为大写锁定,则它可以正常工作。

以下是相关的代码段

    <EditText
    android:id="@+id/etEntry"
    style="@android:style/Widget.EditText"
    android:digits="cvABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789*?.,^+[](|){}\\~-"
    android:hint="@string/searchterm"
    android:imeOptions="actionSearch|flagForceAscii"
    android:inputType="textCapCharacters|textNoSuggestions"
    android:singleLine="true"
    android:visibility="visible"
    tools:hint="Search Term" />

该控件有一个 TextWatcher,stype 值为 3(模式),因此它绕过了修改输入的部分。

        private boolean mWasEdited = false;
    @Override
    public void afterTextChanged(Editable s) {
        if (mWasEdited){
            mWasEdited = false;
            return;
        }
        mWasEdited = true;
        String enteredValue  = s.toString();
        if (stype.getSelectedItemPosition() != 3) { // not pattern
            String newValue = enteredValue.replaceAll("[cv0123456789.,^+-]", "");
            int caret = etTerm.getSelectionStart();
            if (stype.getSelectedItemPosition() != 0 && // not anagram
                    stype.getSelectedItemPosition() != 3) { // and not pattern
                newValue = newValue.replaceAll("[*]", "");
            }
            if (Arrays.asList(2,7,8).contains(stype.getSelectedItemPosition())) { // hooks, begins, ends
                newValue = newValue.replaceAll("[?]", "");
            }
            etTerm.setText(newValue);
            etTerm.setSelection(Math.min(newValue.length(), caret)); // if first char is invalid
        }
    }
};

我假设我要么必须配置控件的键盘方面,要么做一些事情是 onTextChanged。这是一个谜。

标签: androidandroid-softkeyboardandroid-textwatcher

解决方案


我想通了,虽然我不明白为什么需要它,因为我没有更改 EditText 中的任何内容。

我更改了最后几行代码,在条件之前声明插入符号,向内部条件添加返回,然后为 stype 3 添加两行。

    public void afterTextChanged(Editable s) {
        if (mWasEdited){
            mWasEdited = false;
            return;
        }
        mWasEdited = true;
        String enteredValue  = s.toString();
        int caret = etTerm.getSelectionStart();
        if (stype.getSelectedItemPosition() != 3) { // not pattern
            String newValue = enteredValue.replaceAll("[cv0123456789.,^+-]", "");
            if (stype.getSelectedItemPosition() != 0 && // not anagram
                    stype.getSelectedItemPosition() != 3) { // and not pattern
                newValue = newValue.replaceAll("[*]", "");
            }
            if (Arrays.asList(2,7,8).contains(stype.getSelectedItemPosition())) {
                newValue = newValue.replaceAll("[?]", "");
            }
            etTerm.setText(newValue);
            etTerm.setSelection(Math.min(newValue.length(), caret)); 
            return;
        }
        etTerm.setText(enteredValue);
        etTerm.setSelection(Math.min(enteredValue.length(), caret)); 
    }
};

推荐阅读