使用包含标签的 Android 数据绑定 [英] Android Data Binding using include tag
问题描述
上面的例子工作正常,因为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:
main.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"
...." />
main.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"
...." />
main.xml:
<layout xmlns:andr...
...
<include layout="@layout/buttons"
android:id="@+id/buttons"/>
....
这篇关于使用包含标签的 Android 数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!