我想为几个TextWatcher
写EditText
。在任何一个中,我都想将EditText
的值赋给一个变量。像这样:
var variable: String? = null
private inner class CodeTextWatcher : TextWatcher {
override fun afterTextChanged(s: Editable?) {
variable = s?.toString()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
}
对于几个EditText
,我想写一些类似的东西:
private inner class CodeTextWatcher(private val method: (String?) -> Unit) : TextWatcher {
override fun afterTextChanged(s: Editable?) {
method(s?.toString())
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
}
并调用它:
textWatcher1 = CodeTextWatcher {variable1 = s}
textWatcher2 = CodeTextWatcher {variable2 = s}
但是我不能在这里写s
,并且想从s
访问afterTextChanged(s: Editable?)
。有可能吗?
答案 0 :(得分:3)
您尝试过吗:
textWatcher1 = CodeTextWatcher { s -> variable1 = s }
textWatcher2 = CodeTextWatcher { s -> variable2 = s }
或者在这种情况下,甚至
textWatcher1 = CodeTextWatcher { variable1 = it }
textWatcher2 = CodeTextWatcher { variable2 = it }
?