通过DataBinding设置ConstraintLayout组

通过DataBinding设置ConstraintLayout组

本文介绍了如何通过DataBinding设置ConstraintLayout组的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的布局中有2个 Group ,用于控制视图的可见性.
但是,我无法通过DataBinding设置它们的可见性:

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

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

        <variable
            name="viewModel"
            type="co.aresid.book13.fragments.trackinglist.TrackingListViewModel"
            />
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout>

        ...

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

        <androidx.constraintlayout.widget.Group
            android:id="@+id/loading_group"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:visibility="@{viewModel.hideLoadingAndShowContent ? View.GONE : View.VISIBLE, default=visible}"
            app:constraint_referenced_ids="progress_circular"
            />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

hideLoadingAndShowContent 变量是一个 LiveData ,它从我的 ViewModel 中相应的 MutableLiveData 中获取其值:

The hideLoadingAndShowContent variable is a LiveData which gets its value from a corresponding MutableLiveData in my ViewModel:

private val _hideLoadingAndShowContent = MutableLiveData<Boolean>()
val hideLoadingAndShowContent: LiveData<Boolean>
    get() = _hideLoadingAndShowContent

仅在 ViewModel 中设置此 LiveData ,而在 Fragment 类中不会出现.
Fragment 类中,我还设置了 binding.lifecycleOwner :

This LiveData is only set in the ViewModel and does not occur in the Fragment class.
In the Fragment class, I have also set the binding.lifecycleOwner:

binding.lifecycleOwner = viewLifecycleOwner

我错过了什么细节?

推荐答案

我忘记将 ViewModel 传递给我的 Fragment 类中的布局绑定:

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

binding.viewModel = viewModel

这篇关于如何通过DataBinding设置ConstraintLayout组的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 12:38