使用包含标签的 Android 数据绑定 [英] Android Data Binding using include tag

查看:32
本文介绍了使用包含标签的 Android 数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上面的例子工作正常,因为1.0-rc4版本修复了需要不必要的变量的问题.

The above example works properly, because release 1.0-rc4 fixed the issue of needing the unnecessary variable.

我完全按照文档中的描述进行操作 并且它不起作用:

I do exactly as it is described in the documentation and it does not work:

ma​​in.xml:

<layout xmlns:andr...
    <data>
    </data>
       <include layout="@layout/buttons"></include>
....

buttons.xml:

<layout xmlns:andr...>
    <data>
    </data>
    <Button
        android:id="@+id/button"
        ...." />

MyActivity.java:

 ... binding = DataBindingUtil.inflate...
binding.button; ->cannot resolve symbol 'button'

如何获得按钮?

推荐答案

问题是包含的布局不被认为是数据绑定布局.为了使它成为一个,你需要传递一个变量:

The problem is that the included layout isn't being thought of as a data-bound layout. To make it act as one, you need to pass a variable:

buttons.xml:

<layout xmlns:andr...>
  <data>
    <variable name="foo" type="int"/>
  </data>
  <Button
    android:id="@+id/button"
    ...." />

ma​​in.xml:

<layout xmlns:andr...
...
   <include layout="@layout/buttons"
            android:id="@+id/buttons"
            app:foo="@{1}"/>
....

然后您可以通过按钮字段间接访问按钮:

Then you can access buttons indirectly through the buttons field:

MainBinding binding = MainBinding.inflate(getLayoutInflater());
binding.buttons.button

从 1.0-rc4(刚刚发布)开始,您不再需要该变量.您可以将其简化为:

As of 1.0-rc4 (just released), you no longer need the variable. You can simplify it to:

buttons.xml:

<layout xmlns:andr...>
  <Button
    android:id="@+id/button"
    ...." />

ma​​in.xml:

<layout xmlns:andr...
...
   <include layout="@layout/buttons"
            android:id="@+id/buttons"/>
....

这篇关于使用包含标签的 Android 数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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