Challenge 1: Convert Chapter 6's Fragments to a Nav Graph — Solution
// res/navigation/nav_graph.xml
// activity_main.xml — replaces the FrameLayout from Chapter 6
// MainActivity.kt — no more manual FragmentManager call needed at all;
// NavHostFragment loads app:startDestination automatically.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// No FragmentManager.beginTransaction() call needed here anymore —
// the NavHostFragment reads app:startDestination from the nav
// graph and loads WelcomeFragment automatically.
}
}
// WelcomeFragment.kt — the button click listener changes from Chapter 6
binding.viewDetailsButton.setOnClickListener {
findNavController().navigate(R.id.action_welcome_to_details)
}
Notes:
- MainActivity.onCreate no longer needs the
"if (savedInstanceState == null) { ...FragmentManager... }" block from
Chapter 6 at all — NavHostFragment itself handles showing the start
destination and correctly not re-adding it on rotation.
- findNavController().navigate(R.id.action_welcome_to_details) replaces
Chapter 6's "parentFragmentManager.beginTransaction().replace(...).commit()"
— the ID here is the ID from the nav graph, not a destination
ID directly.
- The system Back button now automatically returns from detailsFragment
to welcomeFragment with zero extra code, since app:defaultNavHost="true"
wires it into the nav graph's own back stack.