Huy Duong Tu Huy Duong Tu - 4 months ago 25
Android Question

Display Back Arrow on Toolbar Android

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?
Thanks in advance.

Answer

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
   }
});
Comments