Search code examples
androidandroid-databinding

How can I change a View's visibility based on whether a list is empty or not


I have a List in a model that bounds to a layout using the data-binding lib. How can I change a View's visibility based on the list's isEmpty() condition? Something like android:visibility="@{model.list.isEmpty() ? View.INVISIBLE : View.VISIBLE}"


Solution

  • Ok, although it wasn't clear from the docs, it can be done using custom setters as follows:


    In my model, I had to declare

    @BindingAdapter("android:visibility")
    public static void setVisibility(View view, Model model) {
    
            view.setVisibility(model.getList().isEmpty() ? View.INVISIBLE: View.VISIBLE);
    }
    

    Then, in the layout

     android:visibility="@{model}"
    

    where model is the name of the model's variable in <variable name=""/>