在Kotlin中具有参数的Lambda

时间:2019-10-02 16:35:25

标签: kotlin lambda

我想为几个TextWatcherEditText。在任何一个中,我都想将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?)。有可能吗?

1 个答案:

答案 0 :(得分:3)

您尝试过吗:

textWatcher1 = CodeTextWatcher { s -> variable1 = s }
textWatcher2 = CodeTextWatcher { s -> variable2 = s }

或者在这种情况下,甚至

textWatcher1 = CodeTextWatcher { variable1 = it }
textWatcher2 = CodeTextWatcher { variable2 = it }