So I am using latest NavigationView for navigation drawer along with custom toolbar icon. When I launch my app, I can see my custom icon in the toolbar(Actionbar) but as soon as I switch to different fragment by clicking on Menu item in navigation Drawer, my toolbar reset back to hambuger icon and it never sets my custom icon back no matter how many times I toggle between the NavigationDrawer item. Below it my code -
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
View hView = navigationView.getHeaderView(0);
// Passing each menu ID as a set of Ids because each menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_score, R.id.nav_history,
R.id.nav_setting)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_custom_icon);//your icon here
Additional information if require ...
I changed the order of the above code to see it there is anything that I have got wrong (it was suggested in some old stackoverflow posts).
It is an expected result.
When using
NavigationUI
, the top app bar helpers automatically transition between the drawer icon and the Up icon as the current destination changes
You can add the OnDestinationChangedListener
to set your own icons after your setup method.
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
if (destination.getId() == R.id.nav_xxx){
getSupportActionBar().setHomeAsUpIndicator(R.drawable....);
}
}
});