【问题标题】:Data binding - access individual properties contained in LiveData数据绑定 - 访问 LiveData 中包含的各个属性
【发布时间】:2018-10-15 15:31:39
【问题描述】:
有没有办法用 LiveData 和数据绑定来做这样的事情?
ViewModel 有这个属性:
val weather: LiveData<UnitSpecificCurrentWeatherEntry>
我想在布局中做什么:
<TextView
android:id="@+id/textView"
android:text="@{viewmodel.weather.value.someProperty}"... />
这是否可能,或者我必须将 LiveData 中包含的对象拆分为包含对象的每个属性的多个对象?
【问题讨论】:
标签:
android
kotlin
android-databinding
android-livedata
【解决方案1】:
从 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}"/>