Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataBinding visibility depending on a list size

I am having an object which is using in data binding as a variable.

public class Company {
    private int id;
    private String name;
    private List<Employee> employees;
    private List<Room> rooms;
}


<data>
     <variable
         name="item"
         type="com.blablabla.model.entity.Company"/>

</data>

Want to change visibility of a view depending on a list size (employees), so if the list is null or empty - visibility is GONE, otherwise it is VISIBLE.

What have I tried so far:
1) Setting the visibility directly:

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

In fact visibility is always GONE.

Of course I imported

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

2) Using BindingConverter:

@BindingConversion
    public static int convertCollectionToVisibility(Collection collection) {
        Log.d(TAG, "collection: " + (collection == null ? "null" : collection.size()));
        return collection == null || collection.isEmpty() ? View.GONE : View.VISIBLE;
    }

and then in layout:

android:visibility="@{item.employees}"

Here the log shows, that collection is always null. But it is definitely not

Company company = new Company(1, "Company 1");
List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(i, "Jack", "Floyd"));
        company.setEmployees(employees);
mBinding.setItem(company);

Any thoughts?

like image 315
Leonid Ustenko Avatar asked Apr 06 '17 09:04

Leonid Ustenko


Video Answer


1 Answers

I just faced the same problem and setting visibility directly by item.employees.size (without parentheses) worked for me like a charm.

android:visibility="@{item.employees.size > 0 ? View.VISIBLE : View.GONE}"

like image 103
shift66 Avatar answered Sep 25 '22 19:09

shift66