android - 是否可以在 `FragmentContainerView` 中膨胀包含 `Fragment` 的 View ?

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

我正在尝试膨胀包含 FragmentContainerView 的 View 在被放入布局的 fragment 中。

  • Root View
    • fragment
      • 自定义 View
        • fragment 容器 View

像这样:

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/

相关文章:

android - 在继承 View 的自定义 View 中添加 TextView

android - 从 viewPager fragment 取回用户输入信息 (Kotlin)

android - 如果我以编程方式更改 fragment ,如何更改底部导航图标颜色

android - 为什么在导航中切换屏幕时无法获取 null 作为参数?

android - 在具有透明背景的 fragment 上呈现 fragment

android - 导航 Lint 错误 : This navigation graph is not referenced from any layout files

android - 无法将数据从 HTC android 设备保存到 Firebase!为什么?

android - 如何在不收费的情况下测试IAB

Android 构建错误 : Program type already present: android. support.v7.app.**

android - 销毁android中的先前 fragment