简体   繁体   中英

Android data binding: cannot inject an attribute into “include” tag

I'm trying to create a reusable layout included.xml which then could be injected into other layouts and customized via tag attributes. Here's what I have:

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'
}

As an outcome, the button which I try to inject doesn't contain any image at all.

If in parent.xml I change xmlns:app to res-auto , I have the following error in 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'

Does anybody have an idea why this happens and how to fix this? Thanks.

The problem is that you're not using binding syntax for the variable:

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

should be:

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

Unrelated, but I don't think that includes are allowed as the root element of a layout. I believe that you're going to have to have a normal View surrounding the include.

<?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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM