【问题标题】:Is it possible to inflate a view that contains `FragmentContainerView` inside a `Fragment`?是否可以在“Fragment”中膨胀包含“FragmentContainerView”的视图?
【发布时间】:2020-11-18 07:32:37
【问题描述】:

我正在尝试扩充包含 FragmentContainerView 的视图,该视图位于要放入布局的片段中。

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

像这样:

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

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>

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

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


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

【问题讨论】:

    标签: android android-fragments android-navigation android-navigation-graph


    【解决方案1】:

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

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

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

    【讨论】:

    • 嗨,@ianhanniballake。谢谢回复。我将尝试通过手动添加嵌套的nav_graph 片段来做到这一点。干杯\o/(PS:我在片段之间交换时遇到&lt;fragment&gt;的问题可能是由于您指出的[默默地引起问题]。感谢您提供信息)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    相关资源
    最近更新 更多