5. DataBinding
https://developer.android.com/topic/libraries/data-binding#custom_conversions
数据绑定库是一种支持库,借助该库,您可以使用声明性格式(而非程序化地)将布局中的界面组件绑定到应用中的数据源。
布局通常是使用调用界面框架方法的代码在 Activity 中定义的。例如,以下代码调用 findViewById()
来查找 TextView
微件并将其绑定到 viewModel
变量的 userName
属性:
findViewById<TextView>(R.id.sample_text).apply {
text = viewModel.userName
}
以下示例展示了如何在布局文件中使用数据绑定库将文本直接分配到微件。这样就无需调用上述任何 Java 代码。请注意赋值表达式中 @{}
语法的使用:
<TextView
android:text="@{viewmodel.userName}" />
使用 DataBinding 库设置背景颜色资源或 null
1.可绘制
android:background="@{article.sponsored ? @drawable/sponsored_article_background : null}"
2.作为资源ID
app:backgroundResource="@{article.sponsored ? R.color.sponsored_article_background : 0}"