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

Ankit Suda
Jul 30, 2017 · 1 min read

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 :)

Android Grid

Ankit Suda

Written by

Ankit is self-taught Android App Programmer. He provides Android App Development Tutorials to Android Grid.

Android Grid

Here you can find Android Development Tutorials. Make high quality android apps.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade