How to set title in app bar with Navigation Architecture Component

前端 未结 12 2012
面向向阳花
面向向阳花 2020-12-24 11:40

I was trying out Navigation architecture component and is now having difficulties in setting the title. How do I set the title programmatically and also how it works?

<
12条回答
  •  半阙折子戏
    2020-12-24 12:24

    There is a much easier way to achieve this nowadays with Kotlin and androidx.navigation:navigation-ui-ktx:

    import androidx.navigation.ui.setupActionBarWithNavController
    
    class MainActivity : AppCompatActivity() {
    
        private val navController: NavController
            get() = findNavController(R.id.nav_host_fragment)
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            val binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
            setSupportActionBar(binding.toolbar)
            setupActionBarWithNavController(navController) // <- the most important line
        }
    
        // Required by the docs for setupActionBarWithNavController(...)
        override fun onSupportNavigateUp() = navController.navigateUp()
    }
    

    That's basically it. Don't forget to specify android:label in your nav graphs.

提交回复
热议问题