我正在阅读 android 文档 https://developer.android.com/topic/libraries/data-binding/?hl=en关于数据,我发现了这个:
Kotlin
findViewById<TextView>(R.id.sample_text).apply {
text = viewModel.userName
}
Java
TextView textView = findViewById(R.id.sample_text);
textView.setText(viewModel.getUserName());
我想知道为什么在 kotlin 中使用 apply
而不是 text(aka setText)
函数?
最佳答案
findViewById<TextView>(R.id.sample_text).apply {
text = viewModel.userName
}
上面的代码等同于
val textView = findViewById<TextView>(R.id.sample_text)
textView.text = viewModel.userName
应用函数是一个作用域函数。它的主要用例是 initialization of objects和 Builder-style usage of methods that return Unit
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
关于android - 数据绑定(bind)差异文本或应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52153694/