可以通过使用属性中的应用命名空间和变量名,将变量从容器layout传递到被包含layout的binding中。以下是往被include的name.xml和contact.xml布局文件传递user变量的示例:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable name="user" type="com.example.User"/>
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/name" bind:user="@{user}"/>
<include layout="@layout/contact" bind:user="@{user}"/>
</LinearLayout>
</layout>
数据绑定不支持将include作为merge元素的直接子级。例如,不支持以下布局:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable name="user" type="com.example.User"/>
</data>
<merge><!-- Doesn't work -->
<include layout="@layout/name"
bind:user="@{user}"/>
<include layout="@layout/contact"
bind:user="@{user}"/>
</merge>
</layout>
译者注释:layout/name 和layout/contact 是另外两个支持dataBinding的布局文件,不能是普通的布局文件。其中也需要申明一个变量,变量名称是xxx,那配置的的属性就是 bind:xxx
其他资源
想要学习databinding更多的知识,请参考下面的资源











网友评论