Display Back Arrow on Toolbar

561,361

Solution 1

If you are using an ActionBarActivity then you can tell Android to use the Toolbar as the ActionBar like so:

Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);

And then calls to

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

will work. You can also use that in Fragments that are attached to ActionBarActivities you can use it like this:

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

If you are not using ActionBarActivities or if you want to get the back arrow on a Toolbar that's not set as your SupportActionBar then you can use the following:

mActionBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_action_back));
mActionBar.setNavigationOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       //What to do on back clicked
   }
});

If you are using android.support.v7.widget.Toolbar, then you should add the following code to your AppCompatActivity:

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

Solution 2

I see a lot of answers but here is mine which is not mentioned before. It works from API 8+.

public class DetailActivity extends AppCompatActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

    // toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // add back arrow to toolbar
    if (getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // handle arrow click here
    if (item.getItemId() == android.R.id.home) {
        finish(); // close this activity and return to preview activity (if there is any)
    }

    return super.onOptionsItemSelected(item);
}

Solution 3

There are many ways to achieve that, here is my favorite:

Layout:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:navigationIcon="?attr/homeAsUpIndicator" />

Activity:

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

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // back button pressed
    }
});

Solution 4

you can use the tool bar setNavigationIcon method. Android Doc

mToolBar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);

mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        handleOnBackPress();
    }
});

Solution 5

If you don't want to create a custom Toolbar, you can do like this

public class GalleryActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...  
        getSupportActionBar().setTitle("Select Image");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}                     

In you AndroidManifest.xml

<activity
    android:name=".GalleryActivity"
    android:theme="@style/Theme.AppCompat.Light">        
</activity>

you can also put this android:theme="@style/Theme.AppCompat.Light" to <aplication> tag, for apply to all activities

enter image description here

Share:
561,361
Huy Duong Tu
Author by

Huy Duong Tu

Updated on November 28, 2021

Comments

  • Huy Duong Tu
    Huy Duong Tu over 2 years

    I'm migrating from ActionBar to Toolbar in my application. But I don't know how to display and set click event on Back Arrow on Toolbar like I did on Actionbar.

    enter image description here

    With ActionBar, I call mActionbar.setDisplayHomeAsUpEnabled(true). But there is no the similar method like this.

    Has anyone ever faced this situation and somehow found a way to solve it?

  • ZakTaccardi
    ZakTaccardi over 9 years
    @MrEngineer13 Where did you get the ic_action_back drawable from?
  • MrEngineer13
    MrEngineer13 over 9 years
  • Taeho Kim
    Taeho Kim about 9 years
    If you're using the latest version of appcompat-v7 (21.0.3 or higher), you can use R.drawable.abc_ic_ab_back_mtrl_am_alpha for back arrow drawable, which is included in support library.
  • Quentin S.
    Quentin S. over 8 years
    Please note that getResources().getDrawable(...) is deprecated. You should use ContextCompat.getDrawable(context, ...) instead.
  • honk
    honk over 8 years
    Could you please add some explanation to your answer? Code-only answers are frowned upon on SO.
  • hgoebl
    hgoebl over 8 years
    ActionBarActivity is deprecated (@deprecated Use {@link android.support.v7.app.AppCompatActivity} instead.). Does this mean one has to handle click events manually?
  • Ali Mehrpour
    Ali Mehrpour over 8 years
    Please note method setNavigationOnClickListener() has been added in api level 21 and above
  • Ivvan
    Ivvan about 8 years
    @hgoebl no, just use AppCompatActivity class instead of ActionBarActivity.
  • Kuffs
    Kuffs about 8 years
    This only works if you set the Toolbar as the ActionBar. It is not for standalone toolbars.
  • Milan
    Milan about 8 years
    R.drawable.abc_ic_ab_back_mtrl_am_alpha is now gone in support 23.2.0, use accepted answer instead.
  • Henrique de Sousa
    Henrique de Sousa about 8 years
    Didnt work, cannot find neither R.drawable.abc_ic_ab_back_mtrl_am_alpha neither R.drawable.ic_action_back.
  • Atul
    Atul almost 8 years
    Upvote for onOptionItemSelected() This completes what MrEngineer13 has not covered in his answer.
  • AxA
    AxA almost 8 years
    What to do at onClick(View v)? Just call onBackPressed()
  • Mike76
    Mike76 over 7 years
    Thanks this worked for me. Seems to be better than using click listener, i do not really care about standalone toolbars
  • Pedro Loureiro
    Pedro Loureiro over 7 years
    using the theme attribute is much better than most of the other suggestions in this question
  • Prashanth Debbadwar
    Prashanth Debbadwar over 7 years
    if I set setDisplayHomeAsUpEnabled(true) and setDisplayShowHomeEnabled(true); to enalbe back arrow. Then title is not coming center. I have tried like setting actionBar.setTitle(""); and setDisplayShowTitleEnabled(false). But still not able to solve the issue
  • Bitcoin Cash - ADA enthusiast
    Bitcoin Cash - ADA enthusiast over 7 years
    It is worth noting that those drawables might not be available in some versions of Android (for example, they are not available in certain versions of CyanogenMod). Therefore, the best practice is to COPY them to your project. Otherwise you will inevitably face a few crashes..
  • eugene
    eugene over 7 years
    instead of using setNavigationOnClickListener() you can add case android.R.id.home: inside 'onOptionsItemSelected()`.
  • Bolein95
    Bolein95 about 7 years
    to get "back" icon from support library toolbar.setNavigationIcon(android.support.v7.appcompat.R.dra‌​wable.abc_ic_ab_back‌​_material);
  • Mohamed
    Mohamed about 7 years
    Instead on manually implement onBackPressed(); you can use the proper back navigation provided by google developer.android.com/training/implementing-navigation/…
  • rahulrvp
    rahulrvp about 7 years
    android.support.v7.appcompat.R.drawable.abc_ic_ab_back_mater‌​ial this worked for me getting the back icon.
  • Artemiy
    Artemiy about 7 years
    You can use retrolambda.
  • martinstoeckli
    martinstoeckli almost 7 years
    Thanks for the tip with overriding onSupportNavigateUp(), I cannot think of a reason that the back arrow and the back button should do different things.
  • deejay
    deejay over 6 years
    case android.R.id.home didn't worked for me. so after search for a while, your answer did the trick.. thanks.
  • Rick
    Rick over 6 years
    The google docs link and the getSupportActionBar() worked. Thanks!
  • Nauman Aslam
    Nauman Aslam over 6 years
    This is the most authentic solution especially if you want to use default back icon of android system.
  • Adizbek Ergashev
    Adizbek Ergashev over 6 years
    Thanks for if (item.getItemId() == android.R.id.home)
  • user25
    user25 about 6 years
    it's better to use resource id method then drawable method... mToolbar.setNavigationIcon(R.drawable.ic_arrow_left);
  • filthy_wizard
    filthy_wizard almost 6 years
    using toolbar.setNavigationOnClickListener{ onBackPressed() }
  • filthy_wizard
    filthy_wizard almost 6 years
    dont have the default icon
  • filthy_wizard
    filthy_wizard almost 6 years
    this is what i have and its not working. cant figure it out.
  • Dmitry
    Dmitry over 5 years
    How can I change the color of the arrow?
  • Hack06
    Hack06 over 5 years
    I didn't need the lines under "toolbar" comment line, works nice.
  • Rhusfer
    Rhusfer over 5 years
    a great solution for me. Much cleaner to implement.
  • GabrielBB
    GabrielBB over 5 years
    setSupportActionBar works. Thanks. In my case i also wanted to change the color so i did: toolbar.getNavigationIcon().setColorFilter(getResources().ge‌​tColor(R.color.white‌​), PorterDuff.Mode.SRC_ATOP);
  • aeskreis
    aeskreis over 5 years
    This is the best answer in my opinion, because it doesn't require you to modify the ActionBar state.
  • Fernando Torres
    Fernando Torres over 4 years
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(b‌​oolean)' on a null object reference
  • coderpc
    coderpc over 4 years
    You're my savior! Banging my head since two days. This piece of code helped onSupportNavigateUp()
  • reidisaki
    reidisaki about 4 years
    in my case we were overriding the toolbar and needed to set the navigation icon expliclty thank you
  • Bryan Dormaier
    Bryan Dormaier almost 4 years
    In the case of not setting it as the supportActionBar, this is the best answer for manipulating the toolbar.
  • tenTen
    tenTen over 3 years
    Perfect Solution
  • t3chb0t
    t3chb0t over 3 years
    The only answer that actually shows how navigate back by calling finish() and not just providing a useless comment like // handle back button.
  • noveleven
    noveleven over 2 years
    crash, toolbar is a wrong type
  • Adrian Grygutis
    Adrian Grygutis about 2 years
    Note that you don't need to create your own toolbar, if your theme already apply it