gpt4 book ai didi

android - 数据绑定(bind)差异文本或应用

转载 作者:行者123 更新时间:2023-11-29 18:45:13 25 4
gpt4 key购买 nike

我正在阅读 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 objectsBuilder-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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com