有没有办法用 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/