0

I have three fragments Fragment1 -> Fragment3 -> Fragment4 , So if I click back button in Fragment4 I need to go to Fragment1 using navigation component, I saw popUpto and I didn't understand.

Can you please tell me what I did wrong?

I have used popUpTo property but that doesn't works

 <?xml version="1.0" encoding="utf-8"?>
 <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/navigation_graph"
app:startDestination="@id/first_fragment">

<fragment
    android:id="@+id/first_fragment"
    android:name="com.example.navbottom.ui.navScreen.fragments.FirstFragment"
    android:label="first_fragment"
    tools:layout="@layout/fragment_first">
    <action
        android:id="@+id/action_first_fragment_to_third_fragment"
        app:destination="@id/third_fragment" />
</fragment>

<fragment
    android:id="@+id/third_fragment"
    android:name="com.example.navbottom.ui.navScreen.fragments.ThirdFragment"
    android:label="Third_Fragment"
    tools:layout="@layout/fragment_third" >
    <action
        android:id="@+id/action_third_fragment_to_fourth_fragment"
        app:destination="@id/fourth_fragment" />
</fragment>

<fragment
    android:id="@+id/fourth_fragment"
    android:name="com.example.navbottom.ui.navScreen.fragments.FourthFragment"
    android:label="fragment_fourth"
    tools:layout="@layout/fragment_fourth" >
    <action
        android:id="@+id/action_fourth_fragment_to_first_fragment"
        app:destination="@id/first_fragment"
        app:popUpTo="@id/fourth_fragment"
        app:popUpToInclusive="false"/>
</fragment>
 </navigation>

nothing happens it goes Fragment4 -> Fragment3 -> Fragment1

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Balaji
  • 1,773
  • 1
  • 17
  • 30

1 Answers1

0

I am working on the same problem and I think the solution is

<action
  android:id="@+id/action_third_fragment_to_fourth_fragment"
  app:destination="@id/fourth_fragment"
  app:popUpTo="@id/first_fragment"
  app:popUpToInclusive="false"/>

You want to delete the back stack (or pop stack) when navigating to screen 4.

For 3 -> 4 you don't need inclusive. Your back stack is:

1 -> navigate to 3

1-3 -> navigate to 4, poping everything up to 1

1-4 -> pressing back

1

<action
  android:id="@+id/action_fourth_fragment_to_first_fragment"
  app:destination="@id/first_fragment"
  app:popUpTo="@id/first_fragment"
  app:popUpToInclusive="true"/>

For 4 -> 1 you Need to remove the "old" 1, so you include the popUpToInclusive.

1 -> navigate to 3

1-3 -> navigate to 4, poping everything up to 1

1-4 -> navigating to 1

1-4-1 <- this is why you delete everything including 1.

This way the backstack is "1" again.

ecth
  • 1,215
  • 1
  • 16
  • 33