NavigationUI set custom navigation icon

Viewed 12

With the Jetpack Navigation Library, the usual solutions to change hamburger menu icon in toolbar don't work, including:

toolbar.setNavigationIcon(R.drawable.my_drawer)

or

getSupportActionbar().setIcon(R.drawable.my_drawer)

^ both these methods do NOT work

Looks like NavigationUI library sets the hamburger & back icons in toolbar by its own & the icons are hardcoded in the library.

Is there a way to customize the navigation icon in toolbar when using Jetpack Navigation library?

1 Answers

The Navigation library does not provide any direct way to customize the hamburger or back icons, though there is a workaround.

Add an addOnDestinationChangedListener() to your navController. This is invoked after destination is changed & the lib has changed the icon in toolbar. Now in this callback e can change the toolbar's icon, like so:

navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
            @Override
            public void onDestinationChanged(@NonNull NavController navController, @NonNull NavDestination navDestination, @Nullable Bundle bundle) {
                switch (navDestination.getId()) {
                    case R.id.homeFragment:
                        bottomNavigation.setVisibility(View.VISIBLE);
                        toolbar.setNavigationIcon(R.drawable.ic_hamburger); // <- this
                        break;
                    default:
                        bottomNavigation.setVisibility(View.GONE);
                        break;
                }
            }
        });
Related