【发布时间】:2021-09-03 08:05:57
【问题描述】:
我想利用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()
}
}
我尝试了matching the ViewStub's id/inflatedId attributes 和programmatically setting dimensions/constraints,但都没有解决问题。
让这些部分协同工作我忽略了什么?
【问题讨论】:
标签: android android-constraintlayout android-viewbinding viewstub