Skip to content Skip to sidebar Skip to footer

Include Tag And Databinding

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:

Solution 1:

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><variablename="user"type="com.myproject.model.User"/></data>

Here is detailed answer related to this, refer it

Solution 2:

We know how to use the POJO name and its type on the XML which we are using in setContentView() as a parent view. We should focus on the include tag if we are including any layouts from resource as follows:

<?xml version="1.0" encoding="utf-8"?><layoutxmlns:bind="http://schemas.android.com/apk/res-auto"><data><variablename="user"type="exapmpe.model.User" /></data><android.support.design.widget.CoordinatorLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"><android.support.design.widget.AppBarLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:theme="@style/AppTheme.AppBarOverlay"><android.support.v7.widget.Toolbarandroid:id="@+id/toolbar"android:layout_width="match_parent"android:layout_height="?attr/actionBarSize"android:background="?attr/colorPrimary"app:popupTheme="@style/AppTheme.PopupOverlay" /></android.support.design.widget.AppBarLayout><includelayout="@layout/content_main"bind:user="@{user}" /></android.support.design.widget.CoordinatorLayout></layout>

Here we've use the bind attribute to pass the object to show the detailed info on the content screen. Please make sure the object name should be same in both places like bind:user="@{user}. The content_main.xml should look as follows:

<?xml version="1.0" encoding="utf-8"?><layout><data><variablename="user"type="exapmpe.model.User" /></data><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/content_main" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@{user.firstName + user.lastName}" /></RelativeLayout></layout>

Solution 3:

The problem is that the included layout isn't being thought of as a data-bound layout, take a look here to undertstand how to solve it

Post a Comment for "Include Tag And Databinding"