Dynamic ActionBar title from a Fragment using AndroidX Navigation

前端 未结 12 1682
别那么骄傲
别那么骄傲 2020-12-04 16:16

I am using the new Navigation component from Android Jetpack.

The root Activity setup is quite simple:

override fun onCreate(savedInstanceState: Bund         


        
12条回答
  •  一生所求
    2020-12-04 17:14

    Taking consideration that your host activity is MainActivity, just add the following code to your MainActivity's onCreate fun

    val navController = Navigation.findNavController(this, R.id.nav_host_fragment)
    
    // setting title according to fragment
    navController.addOnDestinationChangedListener { 
        controller, destination, arguments ->
            toolbar.title = navController.currentDestination?.label
    }
    

提交回复
热议问题