是否可以在“Fragment”中膨胀包含“FragmentContainerView”的视图?

Aug*_*rmo 3 android android-fragments android-navigation android-navigation-graph

我正在尝试膨胀一个视图,该视图包含FragmentContainerView正在放入布局中的片段。

  • 根视图
    • 分段
      • 自定义视图
        • 片段容器视图

像这样:

val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.main_content, Frag(), "tag");
transaction.commitNowAllowingStateLoss()
Run Code Online (Sandbox Code Playgroud)

其中Frag创建一个视图,该视图会像这样扩展 xml:

<?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>
Run Code Online (Sandbox Code Playgroud)

但是当我执行代码时,我的应用程序崩溃了:

引起原因:java.lang.IllegalStateException:FragmentManager 已经在执行事务


如何在使用时避免此错误FragmentContainerView(观察:如果我使用<fragment>而不是<androidx.fragment.app.FragmentContainerView>,一切正常)

ian*_*ake 5

childFragmentManager在嵌套片段时,您应该始终、始终使用-childFragmentManager当其父级经历生命周期更改时(我假设是在您调用事务时),永远不会执行事务。

当您使用标签时,这实际上会悄悄地给您带来问题<fragment>,因为这些生命周期事件实际上并不作为交易发生,而是直接作为通货膨胀的一部分发生。使用错误FragmentManager意味着片段及其视图将无法正确保存和恢复其状态。

它失败的原因FragmentContainerView是它FragmentContainerView实际上与您通常所做的相同FragmentTransaction