【发布时间】:2021-12-17 12:58:18
【问题描述】:
所以,我将 BottomNavigationView 与 Jetpack Navigation 绑定在一起。假设我有 4 个底部导航菜单,片段 A、B、C 和 D 和 A 作为起始目的地。从 Fragment A 到 Fragment B,然后到 Fragment C。然后,我按下硬件返回按钮。我希望它返回到片段 B,而不是返回到片段 A(这是起始目的地)。
这是代码:
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment
navController = navHostFragment.navController
binding.navView.setupWithNavController(navController)
如何改变行为?
谢谢~
编辑:
我遵循了 Zain 的回答,并且行为已经符合预期。但,
还有一个问题。假设我有另一个片段 A1,它不是 BottomNavView 片段的一部分。我可以从片段 A 导航到片段 A1。下面是导航图:
<navigation 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:id="@+id/mobile_navigation"
app:startDestination="@+id/navigation_a">
<fragment
android:id="@+id/navigation_a"
android:name="com.example.FragmentA"
android:label=""
tools:layout="@layout/fragment_a">
<action
android:id="@+id/action_navigation_a_to_navigation_a1"
app:destination="@id/navigation_a1"
app:launchSingleTop="true" />
</fragment>
<fragment
android:id="@+id/navigation_a1"
android:name="com.example.FragmentA1"
android:label=""
tools:layout="@layout/fragment_a1" />
<fragment
android:id="@+id/navigation_b"
android:name="com.example.FragmentB"
android:label=""
tools:layout="@layout/fragment_b" />
<fragment
android:id="@+id/navigation_c"
android:name="com.example.FragmentC"
android:label=""
tools:layout="@layout/fragment_c" />
<fragment
android:id="@+id/navigation_d"
android:name="com.example.FragmentD"
android:label=""
tools:layout="@layout/fragment_d" />
</navigation>
如果我从 Fragment A 导航到 Fragment A1,然后导航到 Fragment B 然后按回,它会显示正确的 Fragment,即 A1,但 BottomNavigation 仍将 Fragment B 显示为活动 Fragment 而不是 Fragment A。
【问题讨论】:
-
AFAIK;片段 A1 应该与
BottomNavView的片段相比位于单独的 navGraph 中,因为它不是BottomNavView项目的一部分。BottomnNavView片段应该在单独的 navGraph 中 -
我尝试将其分开,但仍未解决,而且我需要在 1 个图中。
-
这是预期行为,因为您现在的导航是
A (A highlighted) > A1 > B (B highlighted) > Back pressed > A1 (Still B highlighted),因为您没有从BottoomNavView片段返回到另一个片段;但是您从BottoomNavView返回到不在BottoomNavView中的片段。您仍然没有返回 A 来突出显示它。顺便说一下,这是您原始问题的另一个问题 -
但是你可以通过我正在做的一些定制来实现这一点;但我认为这会比这个问题的范围更广;如果您为此提出另一个问题,我们将不胜感激。
-
我明白了。我会尽快打开另一个问题并在此处发布链接。
标签: android android-fragments android-architecture-components android-jetpack-navigation