Use data binding to set View visibility

In your layout:

<data>
    <variable
        name="viewModel"
        type="...."/>
</data>


<View
 android:layout_width="10dp"
 android:layout_height="10dp"
 android:visibility="@{viewModel.saleVisibility, default=gone}"/>

In your ViewModel java code:

@Bindable
public int getSaleVisibility(){
 return mSaleIndecator ? VISIBLE : GONE;
}

The problem is that visibility is an Integer on the View class, this means you have two ways to make this work:

  1. Use the View.VISIBLE and View.GONE constants. https://developer.android.com/topic/libraries/data-binding/index.html#imports
  2. Define a custom setter for visibility that takes a Boolean. https://developer.android.com/topic/libraries/data-binding/index.html#custom_setters

Possible implementation:

@BindingAdapter("android:visibility")
public static void setVisibility(View view, Boolean value) {
    view.setVisibility(value ? View.VISIBLE : View.GONE);
}

Which will make <FrameLayout android:visibility="@{sale}"/> work.


As stated in the Android Developer Guide, you need to do it like this:

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

<FrameLayout android:visibility="@{sale ? View.GONE : View.VISIBLE}"/>