我正在尝试膨胀包含 FragmentContainerView
的 View 在被放入布局的 fragment 中。
- Root View
- fragment
- 自定义 View
- fragment 容器 View
- 自定义 View
- fragment
像这样:
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.main_content, Frag(), "tag");
transaction.commitNowAllowingStateLoss()
哪里Frag
创建一个像这样扩展 xml 的 View :
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:parentTag="android.widget.FrameLayout">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/nav_graph" />
</merge>
但是当我执行代码时,我的应用程序崩溃了:
Caused by: java.lang.IllegalStateException: FragmentManager is already executing transactions
如何在使用 FragmentContainerView
时避免此错误? (观察:如果我使用 <fragment>
而不是 <androidx.fragment.app.FragmentContainerView>
,一切正常)
最佳答案
你应该永远,永远使用childFragmentManager
嵌套 fragment 时 - childFragmentManager
当其父项正在经历生命周期更改时(我假设是在您调用事务时),从不执行事务。
当您使用 <fragment>
时,这实际上会悄悄地给您带来问题。标记为那些生命周期事件实际上并不作为交易发生,而是直接作为通货膨胀的一部分。使用错误FragmentManager
意味着 fragment 及其 View 将无法正确保存和恢复它们的状态。
它失败的原因 FragmentContainerView
是那个FragmentContainerView
实际上也是一样FragmentTransaction
就像你平时做的那样。
关于android - 是否可以在 `FragmentContainerView` 中膨胀包含 `Fragment` 的 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63141245/