我正在使用navigation component
和BottomNavigationView
,遇到一个问题,那就是当我从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>
答案 0 :(得分:3)
根据onNavDestinationSelected()上的文档(setupWithNavController()
选择MenuItem时使用的方法):
默认情况下,后退堆栈将弹出回到导航图的起始目标位置。带有
android:menuCategory="secondary"
的菜单项不会弹出堆栈。
因此,只需将android:menuCategory="secondary"
添加到BottomNavigationView
所使用的每个菜单项中即可。