返回到"导航架构组件"中的相同选项卡时,嵌套片段的状态将丢失

Nir*_*han 10 navigation android bottomnavigationview android-architecture-components android-jetpack

我正在探索上个月在Google I/O 2018中引入的"导航架构组件"概念.

假设我有一个带有底部导航视图和'片段'的活动来托管所有片段: -

<android.support.constraint.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.MainActivity">


        <fragment
            android:id="@+id/root_form"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="androidx.navigation.fragment.NavHostFragment"
            app:navGraph="@navigation/nav_graph"
            app:defaultNavHost="true"
            />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />

</android.support.constraint.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)

我的底部导航视图中有2个动作/标签,分别显示FragmentA和FragmentB.FragmentB有一个嵌套的(子)片段FragmentC,它可以从FragmentB打开.

在我的Activity类中,我使用'setupWithNavController()'函数将底部导航视图与导航控制器链接起来.(包含在'androidx.navigation.ui'包中的Kotlin扩展函数): -

override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)

      bottom_navigation.setupWithNavController(findNavController(R.id.root_form))


 }
Run Code Online (Sandbox Code Playgroud)

一切都按预期工作正常.

但是当用户在FragmentC中并且返回agin到相同的选项卡时,用户导航到FragmentA然后他将只获得FragmentB而不是fragmentC.当用户返回相同的选项卡时,它是底部导航中的常见模式,它应显示他正在查看的最后一个子/嵌套片段.

我知道如果我们有自己的片段事务但是如何在"导航架构组件"域中解决此问题,我们可以处理这个问题?

Mob*_*Dev 0

您可以使用一个容器片段来保存 viewpager 并且是父级的导航位置。当您在 A 或 B 中时,您可以点击 C,然后当您返回时,它将返回到父级,该父级仍将位于您所在的片段选项卡中。

导航图永远不知道 Frag A 或 B,但它知道容器。