1

I am using NavigationUI of android architecture components with bottom navigation in my android app. I have the following situation

  1. The app starts at Fragment A
  2. Initial calculation is done and now I pop out Fragment A by navController.popBackStack()
  3. The app goes to Fragment B (This serves as a 'Home' for the app)
  4. Now there are more fragments say C and D
  5. The user can navigate between B, C and D

Now the problem is in my navigation graph, my starting fragment was A (by defining app:startDestination="@id/fragmentA") but that is now pop out of the activity. Due to this, anytime if I backpress, the app just closes instead going back to the previous fragment. For example, let's say I navigate to Fragment C or D from fragment B and if I press back button, my app will close instead of going to fragment B. If the there way to 'reassign' the startDestination?

I checked the answer to this question which has a similar situation as above but using NavOptions is somehow not working. Is there any other way? Following is the code I used to pop fragment and add nav options

 navController.popBackStack()     
 val navOptions: NavOptions = NavOptions.Builder()
            .setPopUpTo(R.id.homeFragment, true)
            .build()

 navController.navigate(R.id.action_fragmentA_to_fragmentB, null, navOptions)
Dexter
  • 1,421
  • 3
  • 22
  • 43

1 Answers1

0

Use this navigation graph. Hope it will solve your problem.

<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/nav_graph"
    app:startDestination="@id/fragment_a">

    <fragment
        android:id="@+id/fragment_a"
        tools:layout="@layout/fragment_a">

        <action
            android:id="@+id/action_a_to_b"
            app:destination="@id/fragment_b"
            app:popUpTo="@id/fragment_a"
            app:popUpToInclusive="true"/>
    </fragment>

    <fragment
        android:id="@+id/fragment_b"
        tools:layout="@layout/fragment_b">

        <action
            android:id="@+id/action_b_to_c"
            app:destination="@id/fragment_c"/>
    </fragment>

    <fragment
        android:id="@+id/fragment_c"
        tools:layout="@layout/fragment_c">
    </fragment>

</navigation>

Use the following line for navigation:

navController.navigate(R.id.action_a_to_b)
navController.navigate(R.id.action_b_to_c)
Abu Noman
  • 435
  • 3
  • 13