首页 > 解决方案 > ConstraintLayout 的 ViewStub 膨胀

问题描述

我想利用ViewStub来选择性地显示 UI 的一部分。当我的膨胀项目的根是ConstraintLayout时,它不会呈现。 约束布局

但是,如果该根是MaterialCardView,那么它会按预期显示。 MaterialCardView

<!-- my_fragment.xml -->

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/fragmentRootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ViewStub
        android:id="@+id/fragmentViewStub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inflatedId="@+id/fragmentViewStub"
        android:layout="@layout/item"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<!-- item.xml -->

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/itemRootLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/itemLabel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/itemLabelText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
/* MyFragment.kt */

@AndroidEntryPoint
class MyFragment : Fragment(R.layout.my_fragment) {
    private val viewModel: MyViewModel by viewModels()

    private val viewBinding: MyFragmentBinding by viewLifecycleLazy {
        MyFragmentBinding.bind(requireView())
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewBinding.fragmentViewStub.inflate()
    }
}

我尝试匹配 ViewStub 的id/inflatedId属性并以编程方式设置尺寸/约束,但都没有解决问题。

我忽略了让这些作品一起工作的原因是什么?

标签: androidandroid-constraintlayoutandroid-viewbindingviewstub

解决方案


忘记更新我的答案/监督。这在这两种情况下一直按预期工作。

启用了夜间模式,MaterialCardView并且其卡片和内容之间的行为具有自动对比。同时,当ConstraintLayout反转其主题时,标签似乎丢失但确实存在,作为白色背景上的白色文本。


推荐阅读