Android 数据绑定:可以绑定来自 HashMap 的值

Android Databinding: Possible to bind values from a HashMap

我正在将对象的字段(字符串、整数等)绑定到布局文件。例如:

  <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好像不支持。

但是,请问有什么办法吗?非常感谢。

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

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

最简单的方法是:在[].

里面提供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