Android 数据绑定:无法将属性注入 "include" 标记

Android data binding: cannot inject an attribute into "include" tag

我正在尝试创建一个可重复使用的布局 included.xml,然后可以将其注入其他布局并通过标签属性进行自定义。这是我拥有的:

res/layout/parent.xml:

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/com.myself.fancyapp"
    >

    <include layout="@layout/included"
            app:src123="@drawable/my_icon" />

</layout>

res/layout/included.xml:

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >
    <data>
        <variable name="src123" type="android.graphics.drawable.Drawable" />
    </data>

    <android.support.design.widget.FloatingActionButton
        android:src="@{src123}" />
</layout>

app/build.gradle:

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    dataBinding {
        enabled = true
    }
    ....
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}

结果,我尝试注入的按钮根本不包含任何图像。

如果在parent.xml中我把xmlns:app改成res-auto,我在app/build/intermediate/data-binding-layout-out/debug/layout/parent.xml中有如下错误:

Error:(17) No resource identifier found for attribute 'src123' in package 'com.myself.fancyapp'

有人知道为什么会发生这种情况以及如何解决这个问题吗?谢谢。

问题是您没有对变量使用绑定语法:

<include layout="@layout/included"
        app:src123="@drawable/my_icon" />

应该是:

<include layout="@layout/included"
        app:src123="@{@drawable/my_icon}" />

无关,但我认为不允许将包含作为布局的根元素。我相信您将必须有一个围绕包含的正常视图。

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/com.myself.fancyapp"
    >

    <FrameLayout android:layout_width="match_parent"
                 android:layout_height="match_parent">
        <include layout="@layout/included"
                app:src123="@{@drawable/my_icon}" />
    </FrameLayout>
</layout>