Data binding - access individual properties contained in LiveData

半世苍凉 提交于 2019-12-11 15:42:58

问题


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

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

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?


回答1:


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 }

Now, you can use it in your xml:

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


来源:https://stackoverflow.com/questions/52746799/data-binding-access-individual-properties-contained-in-livedata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!