Android数据绑定:可以绑定HashMap中的值

时间:2016-02-25 04:07:02

标签: android android-databinding

我将对象的字段 - 字符串,整数等 - 绑定到布局文件。例如:

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

这很好用。但是,我在该appState对象中也有HashMap个值。

是否可以绑定此值,即android:text="@{appState.thehashmap['thekey']"

目前expression syntax似乎不支持它。

但我想知道,有办法吗?非常感谢。

2 个答案:

答案 0 :(得分:1)

好的,仔细查看文档,它是:

如果你HashMap是这样的话:

  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;
  }

然后您的布局文件可以是这样的:

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

答案 1 :(得分:0)

最简单的方法是:您可以通过在[]内提供key,使用[]运算符直接调用它。

所以,如果你有这样的地图:

<data>
    <import type="java.util.Map"/>

    <variable name="map" type="Map&lt;String, String&gt;"/>

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

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