Android NavGraph android:label"sample tile" not working

212 Views Asked by At

I am working on adding a toolbar title in the NavGraph. I used android:label"sample tile" in the NavGraph, but its not updating the toolbar with the label.

Tried using android:label in the NavGraph, but its not updating the title of the toolbar.

1

There are 1 best solutions below

2
Zain On BEST ANSWER

Using android:label alone won't be fully integrated with jetpack navigation.

In documentation:

NavigationUI contains methods that automatically update content in your top app bar as users navigate through your app. For example, NavigationUI uses the destination labels from your navigation graph to keep the title of the top app bar up-to-date.

So, you need to configure the top app bar to work with NavigationUI and this is done through setupWithNavController().

This section in documentations provides an example:


// Kotlin
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)
}

// Java
@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);

    ...

    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    AppBarConfiguration appBarConfiguration =
            new AppBarConfiguration.Builder(navController.getGraph()).build();
    Toolbar toolbar = findViewById(R.id.toolbar);
    NavigationUI.setupWithNavController(
            toolbar, navController, appBarConfiguration);
}