[Android] How to control the exposure of View using conditional statements in data binding xml


Writing time : 2021-09-01 17:09:34

Let's control the exposure of the View by connecting the boolean type property declared in the ViewModel object to xml.

ViewModel

Declare properties to control exposure in ViewModel.
To not expose the initial state of the View, set the property value to false.

private val _emptyLayoutVisible = MutableLiveData(false)  
val emptyLayoutVisible: LiveData<Boolean>  
    get() = _emptyLayoutVisible  

XML

By using the property value declared in the ViewModel, the visibility property of xml is processed as a conditional statement.

<androidx.constraintlayout.widget.ConstraintLayout  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:background="@color/white"  
    android:visibility="@{viewmodel.emptyLayoutVisible ? View.VISIBLE : View.GONE}"  
    tools:visibility="gone">  
    ...  
</ConstraintLayout>   

Control exposure

If the property declared in the ViewModel is changed, the visibility property of xml is also changed.
In the code below, a value of true is stored if the items list is empty or null, and a value of false is stored if the items list is not empty.

 _emptyLayoutVisible.value = _items.value?.isEmpty() ?: true