Data binding - access individual properties contai

2019-08-26 05:45发布

问题:

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