Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change toolbar back button icon in android material components

I would like to change the default navigate up icon (back button icon) to my custom icon. I not using a drawer, just a simple toolbar and material components

Is this possible?

enter image description here

like image 559
Jama Mohamed Avatar asked May 26 '20 08:05

Jama Mohamed


People also ask

How do I put the back icon on my android toolbar?

Show back button using actionBar. setDisplayHomeAsUpEnabled(true) this will enable the back button. Custom the back event at onOptionsItemSelected. This will enable the back function to the button on the press.

How do I get rid of the back arrow on my android toolbar?

getActionBar(). setDisplayShowHomeEnabled(false); //disable back button getActionBar(). setHomeButtonEnabled(false); In a older android phone, the back button is removed with these two code lines.


1 Answers

If you are using a Toolbar to change the icon just use:

Toolbar toolbar = findViewById(R.id.xxx);
toolbar.setNavigationIcon(R.drawable.xxxx4);
setSupportActionBar(toolbar);

If you are using the ActionBar you can use:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.xxx);

You can also change it overriding in your app theme the homeAsUpIndicator attribute:

  <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
    <item name="homeAsUpIndicator">@drawable/...</item>
  </style>

If you are using the Navigation Components, currently there isn't a way to customize the HomeAsUpIndicator icon, and it is an expected behavior with the Up button displayed when you are on a non-root destination.
There is a workaround adding an addOnDestinationChangedListener after your setup method and checking the destination.
Something like:

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) {
                    //With ActionBar                        
                    //getSupportActionBar().setHomeAsUpIndicator(R.drawable.xxxx);

                    //With a Toolbar
                    toolbar.setNavigationIcon(R.drawable.xxxx);
                }
            }
        });

enter image description here

like image 104
Gabriele Mariotti Avatar answered Oct 10 '22 17:10

Gabriele Mariotti