android - 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。这是一个谜。
解决方案
我想通了,虽然我不明白为什么需要它,因为我没有更改 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));
}
};
推荐阅读
- amazon-web-services - Aws EventBridge 规则模式未与 AWS SAM 正确形成
- wordpress - 自定义帖子类型可以用作帖子作者(在 Wordpress 中)吗?
- google-apps-script - Issue with setValues
- excel - Excel VBA - 链接标签和复选框
- excel - 将列中的最后一个值与多个条件上的空白匹配
- javascript - 将函数作为 prop 传递,然后使用函数组件将其作为参数传递给 ReactJs 中的函数
- swiftui - SwiftUI TextEditor 如何隐藏键盘
- c++ - 指定我不关心函数参数的模板参数的简洁方法?
- javascript - 修改 API 端点返回的响应
- python - 将@property 用作db.cursor 是一种不好的做法吗?