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?
ObservableInt listVisibility = new ObservableInt(View.GONE);
and set it tolistVisibility .set(list.size() > 0 ? View.VISIBLE : View.GONE)
. Inxml
:android:visibility="@{listVisibility}"
. I think you need to update thelistVisibility
whenever yourList
changes, execpt when you use anObservableList
or something like that. – yennsarah Apr 6 '17 at 10:05ObservableInt
because adding more conditions is really easy and you are keeping yourxml
files clean of business logic. – yennsarah Apr 6 '17 at 10:43List
in yourBindingConversion
? Is it also null? – yennsarah Apr 6 '17 at 10:54