Challenge 3: popUpTo Behavior — Solution
// res/navigation/nav_graph.xml — add homeFragment and the popUpTo action
// DetailsFragment.kt — navigating using the new action
binding.goHomeButton.setOnClickListener {
findNavController().navigate(R.id.action_details_to_home)
}
// What pressing Back from homeFragment does as a result:
// popUpTo="@id/welcomeFragment" with popUpToInclusive="true" removes
// welcomeFragment AND everything above it (which includes detailsFragment,
// since it's above welcomeFragment on the stack) from the back stack at
// the moment of navigating to homeFragment. After this navigation, the
// back stack contains ONLY homeFragment — neither welcomeFragment nor
// detailsFragment is still on it. So pressing Back from homeFragment
// does NOT return to detailsFragment or welcomeFragment at all — it
// exits the app (or returns to whatever launched it), exactly like a
// "you can't go back to the login/intro flow" pattern.
Notes:
- popUpToInclusive="true" is what makes welcomeFragment itself get
removed too — without it (popUpToInclusive="false", the default),
welcomeFragment would remain on the stack as the new "bottom," and
Back from homeFragment would return there instead of exiting.
- This is the same underlying mechanism used for a real login flow (per
the chapter's example): once past the destinations meant to be
one-time (an intro sequence, a login screen), popUpTo removes them so
Back can't accidentally re-trigger that flow.