美文网首页
Kotlin CallBack 如何更具 Kt 风味

Kotlin CallBack 如何更具 Kt 风味

作者: markRao | 来源:发表于2021-07-19 11:24 被阅读0次

    在 Kotlin 项目中需要对输入框进行监听时需要写如下监听事件,这不跟 Java 几乎一样嘛,这可一点也不 Kotlin

     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 类用来处理事件

    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 进行类扩展

    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)
            }
    
        })
    }
    

    最后我们可以在页面这样调用了

    binding.etPassword.textChangedListener {
    
                onTextChanged { charSequence, i, i2, i3 ->
                    logI("onTextChanged:"+charSequence.toString())
                }
                
                afterTextChanged {
                    logI("afterTextChanged")
                }
                
            }
    

    相关文章

      网友评论

          本文标题:Kotlin CallBack 如何更具 Kt 风味

          本文链接:https://www.haomeiwen.com/subject/xlbcmltx.html