如何在Android导航组件中管理BottomNavigationView堆栈

时间:2019-10-07 01:18:30

标签: android android-fragments android-architecture-components bottomnavigationview android-jetpack

我正在使用navigation componentBottomNavigationView,遇到一个问题,那就是当我从fragment进入1> 2> 5> 4> 3并按回按钮,我得到fragment 1.我知道这是默认行为,但我不希望这样做,我想将它们保存在backstack中,所以当我按“后退”按钮时,它应该转到{{1} } 4不是1.我一直在尝试和搜索,但找不到任何解决方案。我可以手动将fragment放入fragment中的backstack吗?

我的代码:

  

activity_main.xml

kotlin
  

app_nav.xml

<androidx.constraintlayout.widget.ConstraintLayout
           .......................
           .......................>

            <androidx.appcompat.widget.Toolbar
               ................
               ................/>

            <fragment
                android:id="@+id/app_nav_host_fragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="0dp"
                android:layout_height="0dp"
                app:defaultNavHost="true"
                app:navGraph="@navigation/app_nav"
                ..............
                ............../>
            <com.google.android.material.bottomnavigation.BottomNavigationView
                android:id="@+id/app_bottom_nav_view"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:background="@drawable/white_grey_border_bottom"
                app:menu="@menu/bottom_nav_menu"
                app:labelVisibilityMode="unlabeled"
                ...........
                .........../>

</androidx.constraintlayout.widget.ConstraintLayout>
  

MainActivity.kt

<navigation 
    ...........
    ...........
    android:id="@+id/app_nav"
    app:startDestination="@id/homeFragment">

    <fragment
        android:id="@+id/homeFragment"
        android:name="com.example.instagram_clone.ui.HomeFragment"
        android:label="HomeFragment"
        tools:layout="@layout/fragment_home"/>
    .............
    .............
    .............
    .............
</navigation>

1 个答案:

答案 0 :(得分:3)

根据onNavDestinationSelected()上的文档(setupWithNavController()选择MenuItem时使用的方法):

  

默认情况下,后退堆栈将弹出回到导航图的起始目标位置。带有android:menuCategory="secondary"的菜单项不会弹出堆栈。

因此,只需将android:menuCategory="secondary"添加到BottomNavigationView所使用的每个菜单项中即可。