Include tag and dataBinding

Milad Faridnia picture Milad Faridnia · Oct 5, 2016 · Viewed 22.4k times · Source

I want to use one of my layouts multiple times in the same view using include. Let's say I have a custom.xml including some TextViews.

custom.xml:

 <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

I have included this layout multiple times in parent.xml:

 <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include layout="@layout/custom"
        android:id="@+id/layout1"/>

    <include layout="@layout/custom"
        android:id="@+id/layout2"/>
</LinearLayout>

Now I want to bind my data models to this layout, but the problem is that I don't know how to bind two different data models to layout1 and layout2 since both of them are refrenced from one layout which is custom.xml. As far as I know I can add this tag in my xml layout:

    <data>
       <variable name="user" type="com.myproject.model.User"/>
   </data>

But I need to bind two different data models to custom.xml.

My question is how to have an included layout multiple times in one view and passing different data to them using Data Binding? something like passing data to the layout but not statically binding a model to an xml.

I also found this question which is exactly had the same problem But since Data Binding is released in newer versions of android I am seeking a way to solve the same issue using Data Binding. Here is the part of that question that I have quoted for clarification:

For instance, I have a carefully crafted layout that I want to display three times in my view. Every of those instances would need different values. Since the include is basically a take that XML and paste it here, I'd need something more powerful.

Answer

Ravi picture Ravi · Oct 5, 2016

You can pass that from parent.xml

<include layout="@layout/custom"
    android:id="@+id/layout1"
    app:user="@{object of user1`}"/>

<include layout="@layout/custom"
    android:id="@+id/layout2"
    app:user="@{object of user2`}"/>

Here you need to pass User object from parent.xml

Make sure you have <data> in custom.xml

<data>
   <variable name="user" type="com.myproject.model.User"/>
</data>

Here is detailed answer related to this, refer it