代码
//正则匹配表达,当遇到以下中括号里的内容会停止继续获取,由此得到当前已输入的词
private val exceptRegex = "[ \\n;,.)/(\'\"]".toRegex()
fun initOnWord(editText: EditText, onWord: (String)->Unit) {
editText.doOnTextChanged { text, start, before, count ->
//字符串为null不继续
if (text == null) return@doOnTextChanged
//输入文字继续
val aboveWord = StringBuffer("")
var abovePos = editText.selectionStart - 1
while (true) {
if (abovePos < 0) break
val c = text[abovePos--]
if (exceptRegex.matches(c.toString())) {
break
}
aboveWord.insert(0, c)
}
//aboveWord就是得到的输入的最近的词
onWord(aboveWord.toString())
}
}
使用
initOnWord(edt) {
L.i("得到词语", it)
}
运行结果
![run]()
Comments | NOTHING