597

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Huy Duong Tu
  • 7,798
  • 5
  • 25
  • 46
  • How about http://stackoverflow.com/a/29809691/1644301 – mDroidd Jul 19 '16 at 11:41
  • Use getSupportActionBar() example here http://www.freakyjolly.com/how-to-add-back-arrow-in-android-activity/ – Code Spy Jun 04 '18 at 11:14
  • Related post - [How to display and set click event on Back Arrow on Toolbar](https://stackoverflow.com/q/35810229/465053) – RBT Aug 08 '18 at 11:27

27 Answers27

1043

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;
}
Brais Gabin
  • 5,827
  • 6
  • 57
  • 92
MrEngineer13
  • 38,642
  • 13
  • 74
  • 93
  • @MrEngineer13 Where did you get the ic_action_back drawable from? – ZakTaccardi Nov 15 '14 at 21:59
  • 13
    Googles official Material Design icon repo https://github.com/google/material-design-icons/blob/master/navigation/drawable-xhdpi/ic_arrow_back_black_48dp.png – MrEngineer13 Nov 16 '14 at 15:50
  • 71
    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. – Taeho Kim Feb 24 '15 at 05:23
  • 25
    Please note that getResources().getDrawable(...) is deprecated. You should use ContextCompat.getDrawable(context, ...) instead. – Quentin S. Sep 30 '15 at 18:17
  • 2
    `ActionBarActivity` is deprecated (@deprecated Use {@link android.support.v7.app.AppCompatActivity} instead.). Does this mean one has to handle click events manually? – hgoebl Dec 30 '15 at 16:38
  • 2
    @hgoebl no, just use AppCompatActivity class instead of ActionBarActivity. – Ivvan Feb 17 '16 at 22:15
  • 7
    Didnt work, cannot find neither `R.drawable.abc_ic_ab_back_mtrl_am_alpha` neither `R.drawable.ic_action_back`. – Henrique de Sousa Apr 14 '16 at 16:08
  • What to do at `onClick(View v)`? Just call `onBackPressed()` – rpattabi Jul 24 '16 at 01:59
  • 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 – Prashanth Debbadwar Nov 18 '16 at 06:53
  • 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.. – Bitcoin Cash - ADA enthusiast Dec 21 '16 at 22:02
  • 10
    to get "back" icon from support library `toolbar.setNavigationIcon(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_material);` – Bolein95 Feb 15 '17 at 14:34
  • Instead on manually implement onBackPressed(); you can use the proper back navigation provided by google https://developer.android.com/training/implementing-navigation/temporal.html – Mohamed Feb 26 '17 at 12:55
  • 1
    `android.support.v7.appcompat.R.drawable.abc_ic_ab_back_material` this worked for me getting the back icon. – rahulrvp Mar 28 '17 at 12:07
  • 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. – martinstoeckli Jul 19 '17 at 20:41
  • it's better to use resource id method then drawable method... `mToolbar.setNavigationIcon(R.drawable.ic_arrow_left);` – user25 Mar 18 '18 at 16:50
  • 1
    setSupportActionBar works. Thanks. In my case i also wanted to change the color so i did: toolbar.getNavigationIcon().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP); – GabrielBB Nov 14 '18 at 18:24
  • Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference – Fernando Torres Oct 02 '19 at 21:46
  • You're my savior! Banging my head since two days. This piece of code helped `onSupportNavigateUp()` – coderpc Oct 16 '19 at 00:55
  • in my case we were overriding the toolbar and needed to set the navigation icon expliclty thank you – reidisaki Feb 27 '20 at 21:53
251

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);
}
Vasil Valchev
  • 5,701
  • 2
  • 34
  • 39
241

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
    }
});
Igor Bubelov
  • 5,154
  • 5
  • 25
  • 24
75

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();
    }
});
Sam
  • 6,215
  • 9
  • 71
  • 90
  • 1
    Could you please add some explanation to your answer? Code-only answers are frowned upon on SO. – honk Nov 22 '15 at 11:50
  • 1
    Please note method `setNavigationOnClickListener()` has been added in api level 21 and above – Ali Mehrpour Jan 10 '16 at 13:15
  • 3
    R.drawable.abc_ic_ab_back_mtrl_am_alpha is now gone in support 23.2.0, use accepted answer instead. – Milan Mar 02 '16 at 02:05
38

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

VelocityPulse
  • 613
  • 7
  • 13
Linh
  • 57,942
  • 23
  • 262
  • 279
24
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setNavigationIcon(R.drawable.back_arrow); // your drawable
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed(); // Implemented by activity
        }
    });

And for API 21+ android:navigationIcon

<android.support.v7.widget.Toolbar
    android:navigationIcon="@drawable/back_arrow"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"/>
Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216
20

I used this method from the Google Developer Documentation:

@Override
public void onCreate(Bundle savedInstanceState) {
  ...
  getActionBar().setDisplayHomeAsUpEnabled(true);
}

If you get a null pointer exception it could depend on the theme. Try using a different theme in the manifest or use this alternatively:

@Override
public void onCreate(Bundle savedInstanceState) {
  ...
  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

Then in the manifest, where I set the parent activity for current activity:

<activity
        android:name="com.example.myapp.MyCurrentActivity"
        android:label="@string/title_activity_display_message"
     android:parentActivityName="com.example.myfirstapp.MainActivity" >
    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.myapp.MyMainActivity" />
</activity>

I hope this will help you!

A P
  • 2,131
  • 2
  • 24
  • 36
Paolo Anghileri
  • 457
  • 5
  • 14
20

If your are using the androidx.appcompat.app.AppCompatActivity just use:

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Then just define in the Manifest.xml the parent Activity.

<activity
    android:name=".MyActivity"
    ...>
  <meta-data
      android:name="android.support.PARENT_ACTIVITY"
      android:value=".ParentActivity" />
</activity>

Instead if you are using a Toolbar and you want a custom behavior just use:

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar" 
    app:navigationIcon="?attr/homeAsUpIndicator"
    .../>

and in your Activity:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //....
    }
});
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
17

If you were using AppCompatActivity and have gone down the path of not using it, because you wanted to not get the automatic ActionBar that it provides, because you want to separate out the Toolbar, because of your Material Design needs and CoordinatorLayout or AppBarLayout, then, consider this:

You can still use the AppCompatActivity, you don't need to stop using it just so that you can use a <android.support.v7.widget.Toolbar> in your xml. Just turn off the action bar style as follows:

First, derive a style from one of the NoActionBar themes that you like in your styles.xml, I used Theme.AppCompat.Light.NoActionBar like so:

<style name="SuperCoolAppBarActivity" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">@color/primary_dark</item>
    ...
    ...
</style>

In your App's manifest, choose the child style theme you just defined, like so:

    <activity
        android:name=".activity.YourSuperCoolActivity"
        android:label="@string/super_cool"
        android:theme="@style/SuperCoolAppBarActivity">
    </activity>

In your Activity Xml, if the toolbar is defined like so:

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

Then, and this is the important part, you set the support Action bar to the AppCompatActivity that you're extending, so that the toolbar in your xml, becomes the action bar. I feel that this is a better way, because you can simply do the many things that ActionBar allows, like menus, automatic activity title, item selection handling, etc. without resorting to adding custom click handlers, etc.

In your Activity's onCreate override, do the following:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_super_cool);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(toolbar);
    //Your toolbar is now an action bar and you can use it like you always do, for example:
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} 
Himanshu Lakhara
  • 80
  • 1
  • 1
  • 8
Dhiraj Gupta
  • 9,704
  • 8
  • 49
  • 54
14

In Kotlin it would be

private fun setupToolbar(){
    toolbar.title = getString(R.string.YOUR_TITLE)
    setSupportActionBar(toolbar)
    supportActionBar?.setDisplayHomeAsUpEnabled(true)
    supportActionBar?.setDisplayShowHomeEnabled(true)
}

// don't forget click listener for back button
override fun onSupportNavigateUp(): Boolean {
    onBackPressed()
    return true
}
gprathour
  • 14,813
  • 5
  • 66
  • 90
9
MyActivity extends AppCompatActivity {

    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        toolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(arrow -> onBackPressed());
    }
JJD
  • 50,076
  • 60
  • 203
  • 339
Artemiy
  • 2,702
  • 1
  • 19
  • 13
9

Simple and easy way to show back button on toolbar

Paste this code in onCreate method

 if (getSupportActionBar() != null){

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

Paste this override method outside the onCreate method

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()== android.R.id.home) {

        finish();
    }
    return super.onOptionsItemSelected(item);
}
Waheed Sabir
  • 159
  • 2
  • 4
6

Easily you can do it.

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

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

Credits: https://freakycoder.com/android-notes-24-how-to-add-back-button-at-toolbar-941e6577418e

Euler Tiago
  • 134
  • 2
  • 4
6

First, you need to initialize the toolbar :

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

then call the back button from the action bar :

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

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}
Anubhav
  • 1,984
  • 22
  • 17
5

In the AppCompatActivity for example you can do

public class GrandStatActivity extends AppCompatActivity {

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

    @Override
    public void onResume() {
        super.onResume();

        // Display custom title
        ActionBar actionBar = this.getSupportActionBar();
        actionBar.setTitle(R.string.fragment_title_grandstats);

        // Display the back arrow
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    // Back arrow click event to go to the parent Activity
    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

}
NoWar
  • 36,338
  • 80
  • 323
  • 498
4

In your manifest file for the activity where you want to add a back button, we will use the property android:parentActivityName

        <activity
        android:name=".WebActivity"
        android:screenOrientation="portrait"
        android:parentActivityName=".MainActivity"
        />

P.S. This attribute was introduced in API Level 16.

Sunny Kumar Aditya
  • 2,806
  • 4
  • 26
  • 38
4

If you want to get the back arrow on a Toolbar that's not set as your SupportActionBar:

(kotlin)

val resId = getResIdFromAttribute(toolbar.context, android.R.attr.homeAsUpIndicator)
toolbarFilter.navigationIcon = ContextCompat.getDrawable(toolbar.context, resId)
toolbarFilter.setNavigationOnClickListener { fragmentManager?.popBackStack() }

to get res from attributes:

@AnyRes
fun getResIdFromAttribute(context: Context, @AttrRes attr: Int): Int {
    if (attr == 0) return 0
    val typedValueAttr = TypedValue()
    context.theme.resolveAttribute(attr, typedValueAttr, true)
    return typedValueAttr.resourceId
}
John
  • 1,447
  • 15
  • 16
3

This worked perfectly

public class BackButton extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_box);
        Toolbar chatbox_toolbar=(Toolbar)findViewById(R.id.chat_box_toolbar);
        chatbox_toolbar.setTitle("Demo Back Button");
        chatbox_toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        setSupportActionBar(chatbox_toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        chatbox_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Define Back Button Function
            }
        });
    }
}
RPichioli
  • 3,245
  • 2
  • 25
  • 29
Vikash Sharma
  • 539
  • 8
  • 13
2

Follow 3 steps if you want to handle your problem fastly & simply:

Add file ic_arrow.xml to Drawable folder with some codes below (add codes below into ic_arrow.xml)

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:width="24dp"
android:height="24dp"
android:tint="@color/black"
android:viewportWidth="24"
android:viewportHeight="24"
tools:ignore="ExtraText">
<path
    android:fillColor="@android:color/white"
    android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z" />
</vector>

Add ImageButton to Toolbar (make sure the Toolbar customized, not Titlebar or Statusbar) - You can customize the ImageButton (arrow button) position if you want

<ImageButton
android:id="@+id/arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_arrow"
android:layout_marginTop="15dp"
android:layout_marginStart="15dp"
android:background="@android:color/transparent"
tools:ignore="ContentDescription" />

Add the setArrowButton method to DetailActivity.java (or any xxxActivity.java that you need)

public class DetailActivity extends AppCompatActivity {
    ImageButton arrowButton;

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

    arrowButton = findViewById(R.id.arrow);

    setArrowButton(arrowButton);
}

public void setArrowButton(ImageButton arrowButton) {
    arrowButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish(); //will close the moment activity and return to 
                      //the last activity
        }
    });
   }
}

Done

Preview about arrowButton

enter image description here

Nghien Nghien
  • 189
  • 2
  • 6
1

Add this to activity's xml in layout folder:

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">
    <android.support.v7.widget.Toolbar
        android:id="@+id/prod_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>

Make toolbar clickable, add these to onCreate method:

Toolbar toolbar = (Toolbar) findViewById(R.id.prod_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        finish();
    }
});
Mike Yang
  • 2,581
  • 3
  • 24
  • 27
1

With Kotlin it became:

Xml:

<include
android:id="@+id/tbSignToolbar "
layout="@layout/toolbar_sign_up_in"/>

In your Activity:-

setSupportActionBar(tbSignToolbar as Toolbar?)//tbSignToolbar :id of your toolbar 
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
OhhhThatVarun
  • 3,981
  • 2
  • 26
  • 49
Miled
  • 109
  • 2
  • 13
1

Possibly a more reliable way to get the up icon from your theme (if not using the toolbar as your action bar):

toolbar.navigationIcon = context.getDrawableFromAttribute(R.attr.homeAsUpIndicator)

In order to turn the theme attribute into a drawable I used an extension function:

fun Context.getDrawableFromAttribute(attributeId: Int): Drawable {
    val typedValue = TypedValue().also { theme.resolveAttribute(attributeId, it, true) }
    return resources.getDrawable(typedValue.resourceId, theme)
}
danwilkie
  • 794
  • 6
  • 10
0

If you are using DrawerLayout with ActionBarDrawerToggle, then to show Back button instead of Menu button (and viceversa), you need to add this code in your Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // ...

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.application_name, R.string.application_name);
    mDrawerLayout.addDrawerListener(mDrawerToggle);

    mDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_32dp);
    mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onBackPressed(); // Or you can perform some other action here when Back button is clicked.
        }
    });
    mDrawerToggle.syncState();
    // ...
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mDrawerToggle.onOptionsItemSelected(item))
        return true;

    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        // ...
    }

    return super.onOptionsItemSelected(item);
}

public void showBackInToolbar(boolean isBack) {
    // Remove next line if you still want to be able to swipe to show drawer menu.
    mDrawerLayout.setDrawerLockMode(isBack ? DrawerLayout.LOCK_MODE_LOCKED_CLOSED : DrawerLayout.LOCK_MODE_UNLOCKED);
    mDrawerToggle.setDrawerIndicatorEnabled(!isBack);
    mDrawerToggle.syncState();
}

So when you need to show Back button instead of Menu button, call showBackInToolbar(true), and if you need Menu button, call showBackInToolbar(false).

You can generate back arrow (ic_arrow_back_white_32dp) over here, search arrow_back in Clipart section (use default 32dp with 8dp padding). Just select the color you want.

Borzh
  • 5,069
  • 2
  • 48
  • 64
0

You can always add a Relative layout or a Linear Layout in your Toolbar and place a Image view for back icon or close icon anywhere in toolbar as you like

For example I have used Relative layout in my toolbar

 <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar_top"
                android:layout_width="match_parent"
                android:layout_height="35dp"
                android:minHeight="?attr/actionBarSize"
                android:nextFocusDown="@id/netflixVideoGridView"
                app:layout_collapseMode="pin">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">


                    <TextView

                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Myflix"
                        android:textAllCaps="true"
                        android:textSize="19sp"
                        android:textColor="@color/red"
                        android:textStyle="bold" />


                    <ImageView
                        android:id="@+id/closeMyFlix"
                        android:layout_alignParentRight="true"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        app:srcCompat="@drawable/vector_close" />


                </RelativeLayout>

            </android.support.v7.widget.Toolbar>

And it looks like this:

enter image description here

You can add click listener on that image view from Activity or fragment like this.

  closeMyFlix.setOnClickListener({
            Navigator.instance.showFireTV(  activity!!.supportFragmentManager)
        })
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
0

If you are using JetPack Navigation.

Here is the layout for MainActivity

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                               xmlns:app="http://schemas.android.com/apk/res-auto"
                                               xmlns:tools="http://schemas.android.com/tools"
                                               android:layout_width="match_parent"
                                               android:layout_height="match_parent"
                                               tools:context=".MainActivity">

<androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

</androidx.appcompat.widget.Toolbar>

<fragment
        android:id="@+id/my_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintTop_toBottomOf="@id/toolBar"
        app:layout_constraintBottom_toTopOf="parent"
        app:navGraph="@navigation/nav_graph"/>

SetUp your toolbar in your activity like below in onCreate() of your Activity class.

val navHostFragment = supportFragmentManager
        .findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment? ?: return

val navController = navHostFragment.findNavController()
val toolBar = findViewById<Toolbar>(R.id.toolBar)
setSupportActionBar(toolBar) // To set toolBar as ActionBar
setupActionBarWithNavController(navController)

setupActionBarWithNavController(navController) Will create a back button on the toolBar if needed and handles the backButton functionality. If you need to write a CustomBack functionality, create a callBack as below on your fragment onCreate() method

val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
        // Handle the back button event
    }

From Documentation:https://developer.android.com/guide/navigation/navigation-custom-back

Prakash
  • 7,794
  • 4
  • 48
  • 44
0

maybe it will help someone,I didn't find in the answares the thing I did by the end: with ActionBarDrawerToggle mDrawerToggle; to show the back arrow in toolbar set: mDrawerToggle.setDrawerIndicatorEnabled(false);

and if you want it to show the hamburger in the toolbar:

mDrawerToggle.setDrawerIndicatorEnabled(true);

batsheva
  • 2,175
  • 1
  • 20
  • 32
0

Vasil Valchev codes work fine for me. But if parent activity has set action bar to toolbar by setSupportActionBar(toolbar), there is no need to set it again.

One more thing: getSupportActionBar().setDisplayShowHomeEnabled(true) can be omitted as setting true of false has no effect.

This is the modification:

public class DetailActivity extends AppCompatActivity

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

    // add back arrow to toolbar, no null check too
    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);
}
eos1d3
  • 255
  • 2
  • 10