我正在尝试创建可重复使用的布局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
中出现以下错误:
错误:(17)找不到属性&#39; src123&#39;在包中&#39; com.myself.fancyapp&#39;
有没有人知道为什么会这样,以及如何解决这个问题?感谢。
答案 0 :(得分:3)
问题在于您没有对变量使用绑定语法:
<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>