How to prevent previous fragment to show up after pressing back button using navigation controller?
Navigation offers a popUpTo
and popUpToInclusive
attributes for removing fragments from the back stack as part of a navigate()
operation.
This can be set either in XML:
<!-- Add to your Navigation XML, then use navigate(R.id.go_home) -->
<action
android:id="@+id/go_home"
app:destination="@+id/home_fragment"
app:popUpTo="@+id/destination_to_pop"
app:popUpToInclusive="true"/>
Or set it programmatically:
NavOptions navOptions = new NavOptions.Builder()
.setPopUpTo(R.id.destination_to_pop, true)
.build();
Navigation.findNavController(view).navigate(homeDestination, navOptions)
You can also use the id of a <navigation>
element as well.