How to implement back/up button on Toolbar — Android Studio

Hi Readers,

This is my first post on Android Grid, and in this article you’ll learn “How you can add up button on toolbar.” Well that’s easy, just follow my steps.

There is video on this topic check it out-

There are two methods to add a up button. First I gonna show you the modern method.

We need a toolbar in both methods so add a reference for the toolbar in you onCreate() method.

Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);

METHOD #1

It’s a little code segment you have to add in your activity.

mToolbar.setNavigationIcon(R.drawable.ic_arrow);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
     @Override
public void onClick(View view) {

// Your code
finish();
     }
});

you can change the R.drawable.ic_arrow to your own icon.

METHOD #2

This is a old method but works well.

1)First we need to initialize the toolbar to support action bar-

setSupportActionBar(toolbar);

2)Now we are going to add a call for up button.

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

3)Now we are going to add onClickListener for the up button-

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

finish();
   }
});

Last Words

If you found any mistake in the code or have any question feel free to comment. And please share this post :)