7

Is it really necessary to call

override fun onSupportNavigateUp() = findNavController(R.id.nav_host_fragment).navigateUp()

in my MainActivity ?

Because when I attach the NavHostFragment in my xml it starts from there, but I have seen the Google I/O lecture where they use it to make the start point of the navigation

My question

Where is it necessary to use it ?

Thanks

SNM
  • 5,625
  • 9
  • 28
  • 77

1 Answers1

11

onSupportNavigateUp comes from AppCompatActivity. You should override the method in the same activity where you define your NavHostFragment (probably your MainActivity). You override it so that the NavigationUI can correctly support the up navigation or even the drawer layout menu. AppCompatActivity and NavigationUI are two indepenent components, so you override the method in order to connect the two. Note that if you set a toolbar with the navigation component, i.e., if you do something similar to

override fun onCreate(savedInstanceState: Bundle?) {
  setContentView(R.layout.activity_main)

  // ...

  val navController = findNavController(R.id.nav_host_fragment)
  val appBarConfiguration = AppBarConfiguration(navController.graph)
  findViewById<Toolbar>(R.id.toolbar).setupWithNavController(navController, appBarConfiguration)
}

you don't need to override the onSupportNavigationUp method as Navigation will automatically handle the click events.

You also don't need to override it if you want to handle the toolbar yourself.

Ricardo Costeira
  • 3,171
  • 2
  • 23
  • 23
  • I dont have a toolbar for the momment, my question is just if its a matter implementing it or not because the code works the same without it – SNM Jul 24 '19 at 18:15
  • @CoffeeBreak then no, there's no need to implement it. You'll need it when you have a toolbar and want the navigation component to handle the up button navigation for you. – Ricardo Costeira Jul 24 '19 at 20:10
  • thats where I'm confused, which one is the up button ? I only know about the home button or back button from the toolbar – SNM Jul 24 '19 at 20:11
  • The up button is that little arrow that shows up in the left corner of the toolbar. – Ricardo Costeira Jul 24 '19 at 20:14
  • Thats whay I known as homebutton or toolbar back button, what a weird convention haha – SNM Jul 24 '19 at 20:15
  • 1
    Haha yeah I know, it's kinda weird. It's called "up" because when you press it, you're going "up" in the view hierarchy :) – Ricardo Costeira Jul 24 '19 at 20:19
  • 3
    How can we set this up in a Fragment instead of main Activity? – IgorGanapolsky Dec 11 '19 at 21:58