Odys
Odys

Reputation: 9080

Pass variable to included layout via xml

I want to include a simple layout and pass a static variable to it (string resource here). I followed multiple examples with no luck.

main_layout.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></data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <include android:id="@+id/first_included" layout="@layout/included" app:theValue="@string/firstValue" />
        <include android:id="@+id/first_included" layout="@layout/included" app:theValue="@string/secondValue" />
    </LinearLayout>
</layout>

included.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable name="theValue" type="String" />
    </data>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{theValue}"/>    
</layout>

This gives me the compile error

Error: No resource identifier found for attribute 'theValue' in package 'com.just.example'

I do use databinding in the rest of the project and everything works fine. I could set the value programmatically but this one is static, I want to be able to set it in the layout file.

Upvotes: 3

Views: 3031

Answers (1)

tynn
tynn

Reputation: 39843

In general you have to assign a data binding statement to the attribute you want to use it with. If the attribute itself is well supported with the default XML definitions, it won't fail. But when there's no definition for the attribute (other than the explicit and implicit ones with data binding), the attribute can't be handled and you'll find the error you got.

So whenever you use data binding specific attributes like with the variables of an included layout, you need to define it as

app:myAttr="@{...}"

The Expression Language itself has some nice shortcuts for resources defined. So in you case you can just @string/firstValue inside your expression. This will be resolved to a String which is in turn assigned to the variable theValue in your sublayout.

Upvotes: 4

Related Questions