Search code examples
androidkotlinnavigation-drawerandroid-architecture-navigationandroid-jetpack-navigation

How can i change the text in the app bar?


I am currently working on an app that requires the navigation template from creation. I have been fine-tuning the look of the default navigation template for the app I need to work on. However, there's one thing I have been unable to find a solution to which is to change the text in the app bar. It keeps saying 'Home' but I need to put the title of my app there. I have tried several things such as: setTitle("App title here") in the mainActivity, and in the manifest file I have also tried changing the text in android:label to the App title but nothing I do from the solutions I find online seems to work.

Is there any way I can get around this and change the 'home' text into my App's title? Thanks in advance for any suggestions.

Code inside OnCreate as requested in a comment:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setTitle("Simple Dark Calculator")
    setContentView(R.layout.activity_main)
    val toolbar: Toolbar = findViewById(R.id.toolbar)
    setSupportActionBar(toolbar)



    val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
    val navView: NavigationView = findViewById(R.id.nav_view)
    val navController = findNavController(R.id.nav_host_fragment)
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    appBarConfiguration = AppBarConfiguration(setOf(
            R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow), drawerLayout)
    setupActionBarWithNavController(navController, appBarConfiguration)
    navView.setupWithNavController(navController)
}

Solution

  • Check the doc:

    NavigationUI uses the destination labels from your navigation graph to keep the title of the top app bar up-to-date.

    In your navigation graph change the android:label of the startDestination.

    <navigation 
        app:startDestination="@+id/nav_home">
    
        <fragment
            android:id="@+id/nav_home"
            android:label="@string/menu_home"
            ... >
    
        </fragment>
    

    You can also use the OnDestinationChangedListener to set the title after your setup method:

        navController.addOnDestinationChangedListener { controller, destination, arguments ->
            if (destination.id == R.id.nav_xxx){
                supportActionBar?.title = "My Title"
            }
            //.....
        }