Search code examples
androidandroid-toolbarandroid-architecture-navigation

How to disable toolbar navigation button animation


I'm using toolbar with navigation UI, when navigating from top-level destination to any other destination, the Navigation button appears as an Up button and the title shift to the right. When clicking back the toolbar navigation icon gets hidden and the title back to the start of the toolbar with slide animation.

 var appBarConfiguration = AppBarConfiguration.Builder(
        setOf(
            R.id.homeFragment,
            R.id.moreOptionsFragment,
            R.id.accountDetailsFragment
        )
    ).build()
    navController = findNavController(R.id.navHostMain)
    binding.bottomNavView.setupWithNavController(navController)
    NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration)[enter image description here][1]

How can I disable the animation on title when back to the top-level fragment?


Solution

  • If you use the toolbar inside an activity you can set the toolbar as support action bar by calling setSupportActionBar inside your activity and then set up the action bar with the nav controller by calling NavigationUI.setupActionBarWithNavController.

    You get the animation because NavigationUI uses ToolbarOnDestinationChangedListener class if you set up it with toolbar, and this class has the following method:

    @Override
        protected void setNavigationIcon(Drawable icon,
                @StringRes int contentDescription) {
            Toolbar toolbar = mToolbarWeakReference.get();
            if (toolbar != null) {
                boolean useTransition = icon == null && toolbar.getNavigationIcon() != null;
                toolbar.setNavigationIcon(icon);
                toolbar.setNavigationContentDescription(contentDescription);
                if (useTransition) {
                    TransitionManager.beginDelayedTransition(toolbar);
                }
            }
        }
    

    As you can see, this method uses TransitionManager to animate removing of navigation icon, but it also affects the title. I don't think you can disable it.