android - 返回到 'Navigation Architecture Component' 中的同一选项卡时,嵌套 fragment 的状态丢失

标签 android navigation android-architecture-components bottomnavigationview android-jetpack

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

假设我有一个带有底部导航 View 和一个“fragment ”来托管所有 fragment 的 Activity :-

<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>

我的底部导航 View 中有 2 个操作/选项卡,它们将分别显示 FragmentA 和 FragmentB。 FragmentB 有一个嵌套的(子) fragment FragmentC,可以从 FragmentB 打开。

在我的 Activity 类中,我使用“setupWithNavController()”函数将底部导航 View 与导航 Controller 链接起来。
(包含在“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))


 }

一切都按预期正常工作。

但是如果用户在 FragmentC 中导航到 FragmentA 并返回到同一个选项卡,那么他只会得到 FragmentB 而不是 FragmentC。当用户返回同一选项卡时,它在底部导航中是一种常见模式,它应该显示他正在查看的最后一个子/嵌套 fragment 。

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

最佳答案

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

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

关于android - 返回到 'Navigation Architecture Component' 中的同一选项卡时,嵌套 fragment 的状态丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50983824/

相关文章:

css - IE 6 无法识别当前页面

java - 随机生成形状和颜色并绘制到 Canvas 上

android - 为什么我的 React Native 应用程序需要圆形图标?

java - 从长字符串中提取文本并存储在变量中

android - android中第二次观察viewmodel返回null

具有整洁架构的 Android 分页库

Android 谷歌分页库不工作

android - 可以在 Android 中同步 Animation Drawables 吗?

javascript - 通过替换 Divs(笨拙的)向下钻取导航菜单

android - 操作栏选项卡下划线颜色