如果没有 Kotlin,您将不得不创建一个实现 TextWatcher 的类并覆盖 onTextChanged() 函数,以便能够在文本更改时对其做出反应。
借助 Kotlin,Android Jetpack 提供了一个方便的带有 doOnTextChanged 的 TextView 扩展函数,它允许您使用 lambda 函数简单地对 TextView 的文本更改做出反应。
如果没有 Kotlin 扩展函数,您将通过以下方式对文本更改做出反应:
myTextView.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(s: Editable) {} // do nothing
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} // do nothing
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
// This function is called each time text in the text view is changed
// s is the current text. The other parameters tell you which characters are
// changed since the last time the function was called.
// Put code in here that you want to run each time there's a change.
}
})
使用 Kotlin 扩展函数,它更简洁,因为您不必写出您不使用的额外函数:
myTextView.doOnTextChanged { s, start, before, count ->
// The code in this lambda function is called each time text in the text view is changed
}
Kotlin 文档对初学者来说不是很有用。它的编写就好像您已经熟悉至少一种面向对象的语言一样。 Java 文档对初学者更加友好。尽管语法不同,但有关基本面向对象概念的教学对 Kotlin 和面向对象编程的新手非常有帮助。 You can start here.这里使用的概念是接口.
Java 没有扩展函数。这是 Kotlin 的一项功能,允许为类编写函数而无需覆盖任何内容。在这种情况下,Jetpack 作者使用此功能通过使用无法在 Java 7(Java Android 版本用于其标准代码库)中实现的功能为 Kotlin 用户提供更简洁的语法。如果 Android 是用 Java 8 或更高版本编写的,那么 TextWatcher 可以为两个不常用的函数提供默认的空实现,这样就不需要这个 Kotlin 扩展函数来提供简洁的语法。
请注意,如果您查看此扩展函数的源代码,它实际上仍在覆盖 TextWatcher。它只是在幕后代表您这样做。