You can achieve both of these action with findNavController().NavigateUp()
Given the following graph for example:

<?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/test_nav_graph"
app:startDestination="@id/a">
<fragment
android:id="@+id/a"
android:name="fragment.A"
tools:layout="@layout/a_fragment"
android:label="A" >
<action
android:id="@+id/action_a_to_b"
app:destination="@id/b" />
<action
android:id="@+id/action_a_to_c"
app:destination="@id/c" />
</fragment>
<fragment
android:id="@+id/b"
android:name="fragment.B"
tools:layout="@layout/b_fragment"
android:label="B" >
<action
android:id="@+id/action_b_to_d"
app:destination="@id/d" />
</fragment>
<fragment
android:id="@+id/c"
tools:layout="@layout/c_fragment"
android:name="fragment.C"
android:label="C" >
<action
android:id="@+id/action_c_to_d"
app:destination="@id/d"
app:popUpTo="@id/a"/>
</fragment>
<fragment
android:id="@+id/d"
tools:layout="@layout/d_fragment"
android:name="fragment.D"
android:label="D" />
</navigation>
When you take the path: A->B->D your back stack is A,B,D and when you call NavigateUp()
you go back to B
.
Now the path A->C->D has a minor addition in the action
tag as you can see
<action
android:id="@+id/action_c_to_d"
app:destination="@id/d"
app:popUpTo="@id/a"/>
it has popUpTo, so when you navigate from C
to D
app:popUpTo
tells the Navigation library to pop some destinations off of the back stack as part of the call to navigate()
, so after navigating to D your back stack is A,D and NavigateUp()
takes you back to A