Search code examples
androidandroid-databinding

Dynamic binding of Android view visibility


I have an Android app that uses an online database, when the user uses the app for the first time a display is shown describing how they add their first data entry. Once they do that the list of entries is shown. Next time they start the app they should see the "no entries" display for a moment, until the data is loaded, and then the list of items

My problem is binding the two views to the size of the displayed data list. I have created the list variable in the layout:

<variable name="list" type="java.util.List" />

And in the fragment code the binding is set:

binding.setList(mList) ;

And on the views in the layout I have:

android:visibility="@{list.size() == 0 ? View.GONE : View.VISIBLE}"

When the app is started the binding works correctly, however, when items are added to the list the view visibility does not change.

I would appreciate some input to resolve this, thanks, Sid


Solution

  • There are several ways to solve that:

    1. To dynamically update layout you should use ObservableField
    2. Every time your variable was changed, you need to set it explicitly binding.setList(mList)