我有一个带TextWatcher的EditText . 它应该将文本格式化为人类高度,如5'9“ . 但是当用户犯了错误并想删除输入错误的字符时,TextWather不允许他这样做 . 假设用户想删除”characther the TextWather立即加回 . 下面是代码 . 那么如何允许用户删除EditText中的文本?
private class CustomTextWatcher implements TextWatcher {
private EditText mEditText;
public CustomTextWatcher(EditText e) {
mEditText = e;
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
public void afterTextChanged(Editable s) {
int count = s.length();
String str = s.toString();
if (count == 1) {
str = str + "'";
} else if (count == 3) {
str = str + "\"";
} else if ((count > 4) && (str.charAt(str.length() - 1) != '\"')) {
str = str.substring(0, str.length() - 2)
+ str.charAt(str.length() - 1) + "\"";
} else {
return;
}
mEditText.setText(str);
mEditText.setSelection(mEditText.getText().length());
}
}
2 回答
忽略Karakuri发布的有关您的代码处于错误回调中的事实,您可以添加一个简单的修复程序,您只需要听取用户使用的密钥 .
如果没有对现有代码进行任何实际测试或进一步改进,这似乎可以解决您描述的问题:
From the docs:
您应该在afterTextChanged()中进行任何更改,而不是在其他两个回调中进行任何更改 .