我想我最终找到了一个可行的解决方案,但必须更深入地尝试才能知道这是否存在一些错误或错误。
public abstract class TextListener implements InputFilter {
public abstract CharSequence removeStr(CharSequence removeChars, int startPos);
public abstract CharSequence insertStr(CharSequence newChars, int startPos);
public abstract CharSequence updateStr(CharSequence oldChars, int startPos, CharSequence newChars);
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
CharSequence returnStr = source;
String curStr = dest.subSequence(dstart, dend).toString();
String newStr = source.toString();
int length = end - start;
int dlength = dend - dstart;
if (dlength > 0 && length == 0) {
// Case: Remove chars, Simple
returnStr = TextListener.this.removeStr(dest.subSequence(dstart, dend), dstart);
} else if (length > 0 && dlength == 0) {
// Case: Insert chars, Simple
returnStr = TextListener.this.insertStr(source.subSequence(start, end), dstart);
} else if (curStr.length() > newStr.length()) {
// Case: Remove string or replace
if (curStr.startsWith(newStr)) {
// Case: Insert chars, by append
returnStr = TextUtils.concat(curStr.subSequence(0, newStr.length()), TextListener.this.removeStr(curStr.subSequence(newStr.length(), curStr.length()), dstart + curStr.length()));
} else {
// Case Replace chars.
returnStr = TextListener.this.updateStr(curStr, dstart, newStr);
}
} else if (curStr.length() < newStr.length()) {
// Case: Append String or rrepace.
if (newStr.startsWith(curStr)) {
// Addend, Insert
returnStr = TextUtils.concat(curStr, TextListener.this.insertStr(newStr.subSequence(curStr.length(), newStr.length()), dstart + curStr.length()));
} else {
returnStr = TextListener.this.updateStr(curStr, dstart, newStr);
}
} else {
// No update os str...
}
// If the return value is same as the source values, return the source value.
return TextUtils.equals(source, returnStr) ? source : returnStr;
}
}
从这段代码中,我可以很容易地阻止通过查找在我尝试编辑的文本中选择部分文本进行编辑。