Skip to content Skip to sidebar Skip to footer

How Can I Set A Constraintlayout Group's Visibility Via Databinding?

I have 2 Groups in my layout which control the visibility of my Views. However, I cannot set their visibility via DataBinding:

Solution 1:

I forgot to pass the ViewModel to the layout binding in my Fragment class:

binding.viewModel = viewModel

Solution 2:

Because that android:visibility does not support binding variable observation,

You can create BindingAdapter this way

@BindingAdapter("mutableVisibility")funsetMutableVisibility(view: View, visibility: MutableLiveData<Boolean>) {
    val owner = (view.getParentActivity() ?: view.context) as LifecycleOwner
    if (owner != null) {
        visibility.observe(
            owner,
            Observer { value ->
                  view.visibility = if(value) View.VISIBLE else View.GONE
            })
    }
}

Utility function for getting activity from view.

fun View.getParentActivity(): AppCompatActivity?{
    var context = this.context
    while (context is ContextWrapper) {
        if (context is AppCompatActivity) {
            return context
        }
        context = context.baseContext
    }
    returnnull
}

Then in your XML you can do it like

 <androidx.constraintlayout.widget.Group
            android:id="@+id/content_group"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:visibility="@{viewModel.hideLoadingAndShowContent}"
            app:constraint_referenced_ids="tracking_list_recycler_view"
            />

Post a Comment for "How Can I Set A Constraintlayout Group's Visibility Via Databinding?"