I am binding to an Object's fields--strings, integers etc--to a layout file. For example:
<data>
<variable
name="appState"
type="com.example.app.AppState"
/>
</data>
And
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:title="@{appState.thing}"
/>
This works fine. However, I also have a HashMap
of values in that appState object.
Is it possible to bind to values from this, i.e. android:text="@{appState.thehashmap['thekey']"
?
The current expression syntax does not seem to support it.
But, I wonder, is there a way? Many thanks.
Okay, looking at the docs more closely, it is:
If you HashMap
is something like this:
public HashMap<String, String> thing = new HashMap<String, String>() {{
put("stuff", "yeah");
}};
public HashMap<String, String> getThing() {
return thing;
}
public void setThing(HashMap<String, String> thing) {
this.thing = thing;
}
Then your layout file can be like this:
<data>
<import type="java.util.HashMap"/>
<variable
name="appState"
type="com.example.app.AppState"
/>
</data>
...
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:title='@{appState.thing["stuff"]}'
/>
The simplest method is: You can directly call it with []
operator by providing key
inside []
.
So, if you have an map like this:
<data>
<import type="java.util.Map"/>
<variable name="map" type="Map<String, String>"/>
</data>
...
android:text="@{map[key]}"
Source: https://developer.android.com/topic/libraries/data-binding/index.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With