Search code examples
androidandroid-databinding

Android Databinding default variable value


I have this layout.

<data>
    <import type="android.view.View" />
    <variable
        name="shouldBeVisible"
        type="java.lang.Boolean" />
</data>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="@={shouldBeVisible}" />

    <LinearLayout
        android:layout_width="40dp"
        android:layout_height="30dp"
        android:background="#dd0"
        android:visibility="@{shouldBeVisible ? View.VISIBLE : View.GONE}" />

</LinearLayout>

shouldBeVisible is by default false. Is there a way to make shouldBeVisible true? I want to have LinearLayout visible in this one case.

So far I'm using binding.shouldBeVisible=true


Solution

  • To solve that error you can use several ways:

    1. You can use primitive boolean type with inverted logic (shouldBeVisible -> shouldBeHidden)

    2. Second way is to use boxed Boolean type (as you have now) and set default value in expressions

    3. Third way - manually set it after inflating of binding (as you already do now)

      binding.shouldBeVisible=true

    4. Use default keyword in databining value

    Choose the one best fits your needs.