In the Cupcake app, the app bar shows an arrow to return to the previous screen. This is known as the Up button, and we’ve learned it in previous code labs. The Up button currently doesn’t do anything, so we will fix this navigation bug in the app.
In the MainActivity, we will make navController a class variable so we can use it in another method.
class MainActivity : AppCompatActivity(R.layout.activity_main) { private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val navHostFragment = supportFragmentManager .findFragmentById(R.id.nav_host_fragment) as NavHostFragment navController = navHostFragment.navController setupActionBarWithNavController(navController) } }
Within the same class, we will add code to override the onSupportNavigateUp() function. This code will ask the navController to handle navigating up in the app. Otherwise, fall back to back to the superclass implementation (in AppCompatActivity) of handling the Up button.
override fun onSupportNavigateUp(): Boolean { return navController.navigateUp() || super.onSupportNavigateUp() }
Now we will run the app. The Up button should now work from the FlavorFragment, PickupFragment, and SummaryFragment. As we navigate to previous steps in the order flow, the fragments should show the right flavor and pick-up date from the view model.