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

Data binding - access individual properties contained in LiveData

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

ViewModel 有这个 属性:

val weather: LiveData<UnitSpecificCurrentWeatherEntry>

我在布局中尝试做的事情:

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

这有可能吗?还是我必须将 LiveData 中包含的对象拆分为多个包含对象的每个 属性?

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

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}"/>