Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 403
mmm111mmm Avatar asked Jan 06 '23 14:01

mmm111mmm


2 Answers

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"]}'
      />
like image 190
mmm111mmm Avatar answered Mar 06 '23 19:03

mmm111mmm


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&lt;String, String&gt;"/>

</data>
...
android:text="@{map[key]}"

Source: https://developer.android.com/topic/libraries/data-binding/index.html

like image 40
kirtan403 Avatar answered Mar 06 '23 20:03

kirtan403