我想利用ViewStub来选择性地显示 UI 的一部分。当我的膨胀项目的根是ConstraintLayout时,它不会呈现。
但是,如果该根是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
属性并以编程方式设置尺寸/约束,但都没有解决问题。
我忽略了让这些作品一起工作的原因是什么?