Android数据绑定:可以绑定HashMap中的值 [英] Android Databinding: Possible to bind values from a HashMap

查看:89
本文介绍了Android数据绑定:可以绑定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>

还有

  <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值.

This works fine. However, I also have a HashMap of values in that appState object.

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

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.

推荐答案

好的,仔细研究一下文档,它是:

Okay, looking at the docs more closely, it is:

如果您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;
  }

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

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

这篇关于Android数据绑定:可以绑定HashMap中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆