Can't change toolbar back icon while using navhost

Viewed 1131

I'm trying (without success) to change the back arrow icon on the toolbar when using NavHostFragment. I'm using NavController with toolbar (as you can see here)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)
    val navController = findNavController(R.id.nav_host_fragment)
    appBarConfiguration = AppBarConfiguration(navController.graph)
    setupActionBarWithNavController(navController, appBarConfiguration)
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
    toolbar.setTitleTextColor(resources.getColor(R.color.toolbarTextColor))
    navigation.setupWithNavController(Navigation.findNavController(this, R.id.nav_host_fragment))
}

The navigation is working properly, but i can't seem to change the back icon.

I've already tried using a custom theme. None of the atributes defined have worked so far.

    <style name="ToolbarTheme" parent="@style/ThemeOverlay.AppCompat.ActionBar">
        <item name="android:navigationIcon">@drawable/ic_keyboard_arrow_left_black_24dp</item>
        <item name="android:homeAsUpIndicator">@drawable/ic_keyboard_arrow_left_black_24dp</item>
        <item name="collapseIcon">@drawable/ic_keyboard_arrow_left_black_24dp</item>
        <item name="android:closeIcon">@drawable/ic_keyboard_arrow_left_black_24dp</item>
    </style>

Tried using code:

toolbar.navigationIcon = resources.getDrawable(R.drawable.ic_keyboard_arrow_left_black_24dp)
toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_24dp)
toolbar.navigationIconResource = R.drawable.ic_keyboard_arrow_left_black_24dp

When using code, once the layout is created the back button appears but when i enter another fragment, the icon changes back to the default back icon.

How can i change it?

1 Answers

This feature should be added in the future, currently you can do it by implementing 'OnDestinationChangedListener', and changing the toolbar icon inside the callback (just be sure to add the 'OnDestinationChangedListener' after your setup method), something like this:

navController.addOnDestinationChangedListener { controller, destination, arguments ->
        toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_24dp) //set it here for all the destinations, or inside the switch statement if you want to change it based on destination
        when(destination.id) {
            R.id.mainFragment -> {
              toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_24dp)
            }
            R.id.detailsFragment -> {
              toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_24dp)
            }
        }
    }

Based on this issue:

https://issuetracker.google.com/issues/121078028

Related