【问题标题】:BottomNavigation popBackStack() navigates to startDestination instead previous fragmentBottomNavigation popBackStack() 导航到 startDestination 而不是上一个片段
【发布时间】:2020-06-18 05:06:05
【问题描述】:

我在使用 BottomNavigation + Navigation 组件时遇到问题。基本上,当通过底部导航导航到片段时,popBackStack() 会将应用程序带到 startDestination 而不是上一个片段。

class HomeFragment {
...
    bottomNavigation.setupWithNavController(findNavController(R.id.navHost))
...
}
<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/main_navigation"
    app:startDestination="@id/splashFragment">

    <fragment
        android:id="@+id/splashFragment"
        android:name="SplashFragment"
        android:label="SplashFragment"
        tools:layout="@layout/fragment_splash">
        <action
            android:id="@+id/action_splashFragment_to_A"
            app:destination="@id/A" />
    </fragment>

    <fragment
        android:id="@+id/A"
        android:name="AFragment"
        android:label="AFragment"
        tools:layout="@layout/A">
        <action
            android:id="@+id/action_A_to_B"
            app:destination="@id/B" />
    </fragment>

    <fragment
        android:id="@+id/B"
        android:name="BFragment"
        android:label="BFragment"
        tools:layout="@layout/B">
        <action
            android:id="@+id/actiob_B_to_homeFragment"
            app:destination="@id/homeFragment" /> <!--bottomNavigation implemented in this fragment-->
    </fragment>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/item1" />
    <item
        android:id="@+id/item2" />
    <item
        android:id="@+id/item3" />
</menu>

当我从底部导航导航到 item 框架上的任何一个时,触发 findNavController().popBackStack() 会将应用程序返回到 SplashFragment 并应该返回到 HomeFragment,因为实现了底部导航。

【问题讨论】:

    标签: android android-architecture-navigation android-bottomnavigationview


    【解决方案1】:

    您可以将popBackStack(int destinationId, boolean inclusive) 与这两个参数一起使用。这样,navController 会尝试将控制器的回栈弹出回特定的目的地。

    看到这个link

    您还可以选择弹出导航的后台堆栈。

    看到这个link

    【讨论】:

    • 感谢您的回答,但findNavController().popBackStack(R.id.homeFragment, true) 不起作用意味着片段不会去任何地方,app:popUpTo="@+id/homeFragment" app:popUpToInclusive="true" 也带回SplashScreen
    【解决方案2】:

    在 Splash 的 onDestroyView 或 Home 的 onCreate 中将 startDestination 设置为 home

    findNavController().graph.startDestination = R.id.homeFragment

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      相关资源
      最近更新 更多