android - 数据绑定(bind) - 访问 LiveData 中包含的各个属性

标签 android kotlin android-databinding android-livedata

有没有办法用 LiveData 和数据绑定(bind)来做这样的事情?

ViewModel 有这个属性:

val weather: LiveData<UnitSpecificCurrentWeatherEntry>

我想在布局中做什么:

<TextView
    android:id="@+id/textView"
    android:text="@{viewmodel.weather.value.someProperty}"... />

这是否可以以任何方式实现,或者我是否必须针对所包含对象的每个属性将 LiveData 中包含的对象拆分为多个对象?

最佳答案

从 MVVM 模式的角度来看,这并不完全正确。在您的示例 View 中,需要了解属性路径才能显示数据。最好直接从 ViewModel 提供目标数据。如果您的属性依赖于另一个属性,您可以使用转换:

val weather: LiveData<UnitSpecificCurrentWeatherEntry> = //suppose, we have instantiation here
val someProperty: LiveData<SomePropertyType> = Transformations.map(weather) { it.someProperty }

现在,您可以在 xml 中使用它:

<TextView
    android:id="@+id/textView"
    android:text="@{viewmodel.someProperty}"/>

关于android - 数据绑定(bind) - 访问 LiveData 中包含的各个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52746799/

相关文章:

android - 数据绑定(bind)构建错误,无关输入 '\r' 期望 {COMMENT, SEA_WS, '<' , PI}

android - 无法在自定义对话框中检索 EditText

android - 如何根据大小在表格行中显示图像

java - Signal R native Android 应用程序协商失败

postgresql - jOOQ 查询表达式类型安全,无需自定义转换器

android - 如何让xml中的 `onClick()`调用两个方法?

android - 如何从编辑文本中获取没有小数格式的值

java - 使用 Android Room 时不使用 allowedmainthreadqueries() 的最佳方法是什么?

types - Kotlin赋值运算符重载和类型转换

android - 绑定(bind)到android中的挂起函数