1
votes

Using android jetpack navigation in combination with toolbar and drawer is that the root destination has a hamburger menu icon (to toggle the drawer) and in child fragments there is a back button.

Also an animation exists when opening / closing child fragments on the back arrow.

Now the problem: In one of my child fragments I set a custom navigation back button

toolbar_main.setNavigationIcon(R.drawable.ic_clear)

This also works, but upon closing there is a "glitch" where

  1. The custom icon disappears
  2. The back arrow is visible for a short while (this is the "glitch"
  3. The child closes and the root fragment (with burger icon) is visible again

Question:

Is this "glitch" a bug or do I have to call something other than setNavigationIcon (like ActionBarDrawerToggle or similar) ?

1
Navigation doesn't support custom navigation icons as per this still open feature request, so yeah, your custom icon is going to conflict if you're using any of the NavigationUI methods.ianhanniballake

1 Answers

0
votes

Solution: in each Fragment

override fun onAttach(context: Context) {
    super.onAttach(context)
    val activity = context as BaseActivity
    if (navController.backStack.size > 3) {
        activity.toolbar.setNavigationIcon(getNavigationIcon())
    }
}

more than 3 because:

<navigation
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/navigation"
    app:startDestination="@+id/startFragment"> <----- always +1

    <fragment
        android:id="@+id/startFragment"> <----- startFragment + 1 = 2

    <fragment
        android:id="@+id/fragment_1"> <----- startFragment + 1 = 3

    <fragment
        android:id="@+id/fragment_2"> <----- startFragment + 1 = 3

</navigation>