我有一个edittext。我添加了一个文本观察程序来编辑文本。我听文字变化。如果用户键入的单词以@开头,我会显示用户建议(比如当你键入@和twitter向你显示建议时(
如果文本以普通字母开头,则一切正常。
例如:
hello @random_user how are you
@this also works because there is an empty space before '@'
这个例子很管用。
但是,如果文本以特殊字符开头,则text Watcher会显示不正确的值例如:
@hello_user
#someHashtag
文本观察程序返回错误值。我正在使用onTextChanged
方法来跟踪文本
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Text in edittext is '@user' but I get:
//start = 0, before = 0 and count = 1;
//edittext.getSelectionStart() also returns 1 but cursor is at the end of the line.
//edittext.getText().toString().length() also returns 1 but @user is 5 length.
}
我该如何解决这个问题?
编辑:edittext.postdesc.getText().toString()
只返回第一个字符。例如,如果我的文本是"@user",那么getText方法只返回@
您可以尝试以下解决方法:
class TextWatcherExtended(
private val onTextChanged: (text: CharSequence?, start: Int, before: Int, count: Int) -> Unit
) : TextWatcher {
private var before = 0
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, after: Int) {
this.before = text?.length ?: 0
}
override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {
onTextChanged.invoke(text, start, this.before, count)
}
}