【问题标题】:Android Databinding: Possible to bind values from a HashMapAndroid 数据绑定:可以绑定来自 HashMap 的值
【发布时间】:2016-02-25 04:07:01
【问题描述】:

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

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

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

【问题讨论】:

    标签: android android-databinding


    【解决方案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"]}'
          />
    

    【讨论】:

      【解决方案2】:

      最简单的方法是:你可以直接用[]操作符调用它,在[]里面提供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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-08
        • 1970-01-01
        • 2017-09-30
        • 2020-04-03
        • 2012-02-08
        • 1970-01-01
        • 2019-01-24
        • 2017-10-12
        相关资源
        最近更新 更多