newfivefour newfivefour - 3 months ago 15
Android Question

Android Databinding: Possible to bind values from a HashMap

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.

Answer

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