我正在EditText上实现一个TextWatcher,以便在用户输入新字符时查找和下划线一系列关键字。然而,当选择软键盘上建议/自动完成的单词时,不会将建议的单词添加到EditText中,然后调用onTextChanged函数,而是删除了半个完成的单词。我发现这相当奇怪,因为输入单个字符可以很好地激活onTextChanged功能。对于任何帮助,将不胜感激。
PS.如果有人知道更好的即时处理EditText的方法,请告诉我。
代码:
PS.如果有人知道更好的即时处理EditText的方法,请告诉我。
代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_codify_test);
final EditText editText = (EditText) findViewById(R.id.editText_codifyTest);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!checked) { //stop infinite loop
checked = true;
cursorPosition = editText.getSelectionStart(); //get cursor position before text modification
codifyText(editText);
} else {
checked = false;
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
//Find and underline keywords
private void codifyText(EditText editText) {
String plainText = editText.getText().toString() + " ";
int prevWhiteSpace = 0;
final Context context = this;
SpannableString codifiedText = new SpannableString(plainText.substring(0, plainText.length() - 1));
if (codifiedText.length() == 0) return;
for (int i = 0; i < plainText.length(); i ++){
if (Character.isWhitespace(plainText.charAt(i))){
String currWord = plainText.substring(prevWhiteSpace, i);
if (isKeyWordInDataBase(currWord)) {
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View view) {
}
};
codifiedText.setSpan(clickableSpan, prevWhiteSpace, i, 0);
}
prevWhiteSpace = i + 1;
}
}
editText.setMovementMethod(LinkMovementMethod.getInstance());
editText.setText(codifiedText, TextView.BufferType.SPANNABLE);
editText.setSelection(cursorPosition); //set cursor to position prior to edit
}