Android Databinding: Possible to bind values from a HashMap

*爱你&永不变心* 提交于 2019-12-08 04:14:01

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/35618116/android-databinding-possible-to-bind-values-from-a-hashmap

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