Android-如果文本以特殊字符开头例如@或#,则EditText文本查看器显示不正确的值

问题描述

我有一个edittext。我已将文本监视程序添加到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?,count: Int,after: Int) {
        this.before = text?.length ?: 0
    }

    override fun onTextChanged(text: CharSequence?,count: Int) {
        onTextChanged.invoke(text,start,this.before,count)
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...