Search code examples
androidandroid-layoutcheckboxandroid-databinding

View visibility dependent on CheckBox in data binding


I want to set a view visibility dependent on a CheckBox checked status. Something like we do in preference.xml.

Currently i am doing

<?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="isScheduleChecked"
            type="java.lang.Boolean"/>

        <variable
            name="activity"
            type="com.amelio.ui.activities.ActivityCart"/>

    </data>

    <LinearLayout
        style="@style/llDefault"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onCheckedChanged="@{()-> isScheduleChecked}"
            android:text="Checkbox"/>

        <LinearLayout
            style="@style/llDefault"
            android:padding="@dimen/space_small"
            android:visibility="@{isScheduleChecked ? View.VISIBLE : View.GONE, default = gone}"
            >

        </LinearLayout>

    </LinearLayout>

</layout>

This does not work. I think android:onCheckedChanged="@{()-> isScheduleChecked}" this line is not working. What i am doing wrong? Some tell me best way to implement it.

Currently i am changing isScheduleChecked by my activity in java code like binding.setIsScheduleChecked(true/false); but i don't to write code in java class for just set visibility.


Solution

  • I did not know the Easiest Way before.

    You can refer to id in data binding. No need to take another variable.

        <CheckBox
            android:id="@+id/checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Checkbox"/>
    
        <LinearLayout
            style="@style/llDefault"
            android:padding="@dimen/space_small"
            android:visibility="@{checkbox.isChecked() ? View.VISIBLE : View.GONE, default = gone}"
            >
    
        </LinearLayout>
    

    Reasons that may cause issue

    1. Ids are always generated in camelCase. like id is check_box then you will use checkBox.isChecked().
    2. You must import View in layout to use it View.VISIBLE

      <data>
          <import type="android.view.View"/>
      </data>
      

    If you are having any other issue then you can comment.