1

我正在尝试对包含FragmentContainerView在被放入布局中的片段内部的视图进行膨胀。

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

像这样:

val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.main_content, Frag(), "tag");
transaction.commitNowAllowingStateLoss()

whereFrag创建一个像这样膨胀 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>

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

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


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

4

1 回答 1

4

你应该总是,总是childFragmentManager在嵌套片段时使用——childFragmentManager当它的父级经历生命周期变化时(我假设是当你调用你的事务时),它永远不会执行事务。

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

它失败的原因FragmentContainerView是它FragmentContainerView实际上FragmentTransaction和你通常做的一样。

于 2020-07-28T19:24:32.250 回答