在 Kotlin 项目中需要对输入框进行监听时需要写如下监听事件,这不跟 Java 几乎一样嘛,这可一点也不 Kotlin
代码语言:javascript复制 binding.etLoginName.addTextChangedListener(object: TextWatcher{
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
TODO("Not yet implemented")
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
TODO("Not yet implemented")
}
override fun afterTextChanged(s: Editable?) {
TODO("Not yet implemented")
}
})
于是乎,我们可以改造一下,用 DSL 的方式来处理,先申明 TextWatcherDSL 类用来处理事件
代码语言:javascript复制typealias _beforeTextChanged = (CharSequence?, Int, Int, Int) -> Unit
typealias _onTextChanged = (CharSequence?, Int, Int, Int) -> Unit
typealias _afterTextChanged = (Editable?) -> Unit
class TextWatcherDSL {
var beforeTextChanged: _beforeTextChanged? = null
var onTextChanged: _onTextChanged? = null
var afterTextChanged: _afterTextChanged? = null
fun beforeTextChanged(beforeTextChanged: _beforeTextChanged){
this.beforeTextChanged = beforeTextChanged
}
fun onTextChanged(onTextChanged: _onTextChanged){
this.onTextChanged = onTextChanged
}
fun afterTextChanged(afterTextChanged: _afterTextChanged){
this.afterTextChanged = afterTextChanged
}
}
然后再对 TextView 进行类扩展
代码语言:javascript复制inline fun TextView.textChangedListener(block: TextWatcherDSL.() -> Unit){
val dsl = TextWatcherDSL()
dsl.block()
addTextChangedListener(object : TextWatcher{
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
dsl.beforeTextChanged?.invoke(s, start, count, after)
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
dsl.onTextChanged?.invoke(s, start, before, count)
}
override fun afterTextChanged(s: Editable?) {
dsl.afterTextChanged?.invoke(s)
}
})
}
最后我们可以在页面这样调用了
代码语言:javascript复制binding.etPassword.textChangedListener {
onTextChanged { charSequence, i, i2, i3 ->
logI("onTextChanged:" charSequence.toString())
}
afterTextChanged {
logI("afterTextChanged")
}
}