数据绑定-访问LiveData中包含的各个属性 [英] Data binding - access individual properties contained in LiveData

查看:432
本文介绍了数据绑定-访问LiveData中包含的各个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用LiveData和数据绑定执行类似的操作?

Is there a way to do something like this with LiveData and data binding?

ViewModel具有此属性:

ViewModel has this property:

val weather: LiveData<UnitSpecificCurrentWeatherEntry>

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

What I'm trying to do in the layout:

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

这是否有可能,或者我是否必须针对包含的对象的每个属性将LiveData中包含的对象拆分为多个对象?

Is this possible in any way or do I have to split the object contained in LiveData into multiple ones for each property of the contained object?

推荐答案

从MVVM模式的角度来看,这并不完全正确.在您的示例视图中,需要了解有关属性路径的信息才能显示数据.最好直接从ViewModel提供目标数据.如果您的财产是相互依赖的,则可以使用Transformations:

From the point of view of MVVM pattern it's not entirely correct. In your example view require know about property path to display data. Preferable to provide target data directly from ViewModel. If your property is depend from another, you can use Transformations:

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

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

Now, you can use it in your xml:

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

这篇关于数据绑定-访问LiveData中包含的各个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆