Search code examples
androidandroid-layoutandroid-databinding

Android Data Binding: Is there a good way to show / hide an includes tag?


I have just begun to mess around with data binding in android. Ideally I would like to have a root xml file that contains some generic xml elements and then its inner contents can be one of three xml files something like this

<data>
  <variable name="action" type="com.example.android.action"/>
</data>

<TextView>
<TextView>
<!--Only show one of these includes based on the binding data-->

<!-- if action.item -->
<include layout="item.xml"
 bind:item="@{action.item}">

<!-- else if action.udpate -->
<include layout="update.xml"
 bind:update="@{action.update}">

<!-- else if action.video -->
<include layout="video.xml"
 bind:video="@{action.video}">

<TextView>
... etc

So basically based on what child object exists inside of action (either item, update or video) show the layout for it and bind the view but do not show the other includes. Should I just use android's View:Visibility or is there something with includes that I am overlooking?


Solution

  • Should I just use android's View:Visibility

    Yes, best approach is checking boolean in data binding layout and set visibility accordingly like below.

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        >
    
        <data>
    
            <import type="android.view.View"/>
    
            <variable
                name="action"
                type="com.example.android.action"/>
        </data>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    
            <include
                layout="@layout/item"
                android:visibility="@{action.item ? View.VISIBLE: View.GONE}"/>
    
            <include
                layout="@layout/update"
                android:visibility="@{action.someOtherObject!=null ? View.VISIBLE: View.GONE}"/>
    
        </LinearLayout>
    </layout>
    

    Here you can check NULL or Boolean as above.