140

In many apps (Calendar, Drive, Play Store) when you tap a button and enter a new activity, the icon in the title bar turns into a back button, but for the app I am making, it doesn't do that. How do I make that icon take you back to the previous screen?

Drew
  • 12,578
  • 11
  • 58
  • 98
  • Try getSupportActionBar() in OnCreate example here http://www.freakyjolly.com/how-to-add-back-arrow-in-android-activity/ – Code Spy Jun 04 '18 at 11:02

26 Answers26

173

There are two simple steps to create a back button in the title bar:

First, make the application icon clickable using the following code in the activity whose title bar you want to have a back button in:

ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

After you have added the above code, you will see a back arrow appear to the left of the application icon.

enter image description here

Second, after you have done the above, you still have to create code that will take advantage of the click event. To do so, be aware that, when you actually click on the application icon, an onOptionsItemSelected method is called. So to go back to the previous activity, add that method to your activity and put Intent code in it that will return you to the previous activity. For example, let's say the activity you are trying to go back to is called MyActivity. To go back to it, write the method as follows:

public boolean onOptionsItemSelected(MenuItem item){
    Intent myIntent = new Intent(getApplicationContext(), MyActivity.class);
    startActivityForResult(myIntent, 0);
    return true;
}

That's it!

(In the Android developers API, it recommends messing around with the manifest and adding stuff like android:parentActivityName. But that doesn't seem to work for me. The above is simpler and more reliable.)

<meta-data
      android:name="android.support.PARENT_ACTIVITY"
      android:value=".MainActivity" />

And in your Activity

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nbro
  • 15,395
  • 32
  • 113
  • 196
Luke
  • 2,751
  • 1
  • 17
  • 20
  • 26
    You explained well but if ain't wrong in your onOptionItemSelected you should just call finish(); in your case startActivityForResult will launch second activity and when you will press back from second activity you will be thrown back to first activity(where yo pressed action bar icon) – Yahya Arshad Nov 04 '13 at 04:52
  • 11
    Moreover, you should do that only if item.getItemId() is android.R.id.home – Alex Bitek Jun 12 '15 at 18:22
  • 2
    As AS states: "Method invocation 'actionBar.setDisplayHomeAsUpEnabled(true)' may produce java.lang.NullPointerException" – statosdotcom Jun 29 '16 at 15:26
  • For those who need to _hide_ the up button use `setDisplayHomeAsUpEnabled(false);` – Eido95 Jan 26 '17 at 18:38
  • 1
    Warning! With a ToolBar actionBar returns null with crash. See answers below. – CoolMind Dec 15 '17 at 13:18
  • 9
    getActionBar() didnt work for me, app just crashes. getSupportActionBar() did work. – john k Oct 09 '18 at 15:15
  • At a glance, the snippet seems to *creates* a new `MyActivity`. Why does it *return* to the previous one instead of creating a new one? – Minh Nghĩa Jun 22 '21 at 09:04
66

use this code

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

after that write this code in onOptionsItemSelected method

  int id = item.getItemId();

     if (id==android.R.id.home) {
        finish();
    }
Paul Verest
  • 60,022
  • 51
  • 208
  • 332
anupam sharma
  • 1,705
  • 17
  • 13
61

I have finally managed to properly add back button to actionbar/toolbar

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
    }

    return super.onOptionsItemSelected(item);
}

public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}
Lucy Fair
  • 901
  • 7
  • 9
20

1.- Add the activity to AndroidManifest.xml and make sure to provide the meta-data:

<activity
    android:name="com.example.myfirstapp.DisplayMessageActivity"
    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.myfirstapp.MainActivity" />
</activity>

2.- Add the following code to the onCreate method of the activity:

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

3.- Override the onOptionsItemSelected and use NavUtils.navigateUpFromSameTask() static method to navigate throw the stack.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

However, using navigateUpFromSameTask() is suitable only when your app is the owner of the current task (that is, the user began this task from your app). If that's not true and your activity was started in a task that belongs to a different app, then navigating Up should create a new task that belongs to your app, which requires that you create a new back stack.

spacebiker
  • 3,777
  • 4
  • 30
  • 49
13

If your activity does extend Activity

public class YourActivity extends Activity {

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

        getActionBar().setHomeButtonEnabled(true);

        [...]
    }

    [...]
}

If your action extends AppCompatActivity

public class YourActivity extends AppCompatActivity {

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

            getSupportActionBar().setHomeButtonEnabled(true);

            [...]
        }

        [...]
    }

Nothing more to do, See Add up action

[OPTIONAL] To explicitly define parent activity modify your Manifest.xml like this:

<application ... >
    ...
    <!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name="com.example.myfirstapp.YourActivity "
        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.myfirstapp.MainActivity" />
    </activity>
</application>

See Specify the Parent Activity

tot
  • 162
  • 1
  • 10
11

First you need to write this codes

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

Then add this line in manifest

 <activity android:name=".MainActivity"
            android:parentActivityName=".PreviousActivity"></activity>

I think it will work

Shahriar Ahmad
  • 149
  • 1
  • 3
9

first of all in onCreate Function add the following line

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and then add the following function in the code:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }
M Anees
  • 31
  • 1
  • 1
7

If your activity extends AppCompatActivity you need to override the onSupportNavigateUp() method like so:

public class SecondActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_second);
       Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
       setSupportActionBar(toolbar);
       getSupportActionBar().setHomeButtonEnabled(true);
       getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       ...
   }

   @Override
   public void onBackPressed() {
       super.onBackPressed();
       this.finish();
   }

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

Handle your logic in your onBackPressed() method and just call that method in onSupportNavigateUp() so the back button on the phone and the arrow on the toolbar do the same thing.

Ruzin
  • 1,645
  • 2
  • 14
  • 14
6

If you are using the new support library for 5.1 in android studio, you can instead use this on your AppCompatActivity

 ActionBar actionBar = getSupportActionBar();
 actionBar.setHomeButtonEnabled(true);
 actionBar.setDisplayHomeAsUpEnabled(true);
 actionBar.setHomeAsUpIndicator(R.mipmap.ic_arrow_back_white_24dp);
 actionBar.setDisplayShowHomeEnabled(true);

cheers.

ralphgabb
  • 10,298
  • 3
  • 47
  • 56
6

After a quality time I have found, theme option is the main problem in my code And following is the proper way to show the toolbar for me

In AndroidManifest file first you have to change your theme style

Theme.AppCompat.Light.DarkActionBar
to 
Theme.AppCompat.Light.NoActionBar

then at your activity xml you need to call your own Toolbar like

<androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:elevation="4dp"/>

And then this toolbar should be called in your Java file by

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

And for toolbar showing U should check the null to avoid NullPointerException

if(getSupportActionBar() != null){
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

For Home activity back add this

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

        return super.onOptionsItemSelected(item);
    }

OR for your desired activity back

public boolean onOptionsItemSelected(MenuItem item){
    Intent myIntent = new Intent(getApplicationContext(), YourActivity.class);
    startActivityForResult(myIntent, 0);
    return true;
}
Mimu Saha Tishan
  • 2,402
  • 1
  • 21
  • 40
6
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.YourxmlFileName);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

  public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id==android.R.id.home) {
            finish();
            return true;
        }
        return false;
    }
S.Adikaram
  • 480
  • 5
  • 12
  • This is exactly what I was looking for, other answers assume that I want to go back to activity X but I actually want to go back the the previous activity. – Denis Nutiu Nov 29 '20 at 14:54
5

The simplest way and best practice as google explains in here :

1.Add a parent for your childActivity in the AndroidManifest.xml :

<activity 
        android:name=".ChildActivity"
        android:parentActivityName=".ParentActivity" >
</activity>

2.Activate the back button in your childActivity :

myActionOrActionSupportBar.setDisplayHomeAsUpEnabled(true);

Worked for me, I hope it works for you too.

luke8800gts
  • 398
  • 3
  • 7
5

I saw so much complexes answer, so this is my code. Working here. You can achieve this in two ways.

1) Stardard android compatiblity

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NavUtils;

import android.view.MenuItem;
import android.view.View;

public class EditDiscoveryActivity extends AppCompatActivity {

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

        /*toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });*/
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

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

}

2) Use a custom icon

If you want to use code in comments you just have to add this file in drawable, called ic_arrow_white_24dp.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
    <path
        android:fillColor="#ffffff"
        android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z"/>
    </vector>

With this code.

toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });

Hope it will helps some people here !

Zhar
  • 3,330
  • 2
  • 24
  • 25
3

All you need to do in 2020:
(considering you want to return to the MainActivity)

protected void onCreate(Bundle savedInstanceState){
    ...
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

public boolean onOptionsItemSelected(MenuItem item) {
    Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
    startActivityForResult(myIntent, 0);
    return true;
}
James Dunn
  • 456
  • 4
  • 9
  • 1
    That's interesting, but you are assuming that we want to get back to MainActivity. How would you redirect to any previous activity? – mayid May 01 '20 at 15:02
2

Light-weighted version without using ActionBarActivity that still has the same bahaviors here:

public class ToolbarConfigurer implements View.OnClickListener {
    private Activity activity;

    public ToolbarConfigurer(Activity activity, Toolbar toolbar, boolean displayHomeAsUpEnabled) {
        toolbar.setTitle((this.activity = activity).getTitle());
        if (!displayHomeAsUpEnabled) return;
        toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
        toolbar.setNavigationOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        NavUtils.navigateUpFromSameTask(activity);
    }
}

Usage: Put new ToolbarConfigurer(this, (Toolbar) findViewById(R.id.my_awesome_toolbar), true); in onCreate.

Mygod
  • 2,077
  • 1
  • 19
  • 43
2

You need to add the below mentioned code in the manifest file. Search for the activity in which you want to add the back arrow functionality. If you find the one then fine or create the activity

<activity android:name=".SearchActivity">

</activity>

Then add the following three lines of code in between.

<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.raqib.instadate.MainActivity" />

And don't forget to add this piece of code in onCreate(); method of your particular activity in which you need back arrow.

        Toolbar toolbar = (Toolbar) findViewById(R.id.searchToolbar);
    setSupportActionBar(toolbar);
    try{
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }catch(NullPointerException e){
       Log.e("SearchActivity Toolbar", "You have got a NULL POINTER EXCEPTION");
    }

This is how i solved the problem. Thanks.

Muhammad Raqib
  • 304
  • 3
  • 12
2

For kotlin :

   override fun onOptionsItemSelected(item: MenuItem): Boolean {
        onBackPressed();
        return true;
    }
Raluca Lucaci
  • 2,058
  • 3
  • 20
  • 37
2

I needed to mix some answers to get the right answer for me because my app has 3 activities that can go and back at any time. Activity1 > Activity2 > Activity3. When I was doing something on my activity3, the back button was backing correctly to Activity2. However, from the Activity2, using finish(), it was backing to Activity3 and not Activity1. And I'm extending AppCompatActivity. So, my solution was:

public class Activity2 extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            ...

            getSupportActionBar().setHomeButtonEnabled(true);
        }
    }

on AndroidManifest.xml:

<activity android:name=".activities.Activity2"
           android:parentActivityName="com.example.appname.activities.Activity1">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.appname.activities.Activity1" />
        </activity>

and finally, the action button on my menu (actionbar):

public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            ...

            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;

        }

        return super.onOptionsItemSelected(item);

    }

Using NavUtils.navigateUpFromSameTask(this); worked for me, instead of finish().

Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28
Gi Tavares
  • 367
  • 6
  • 15
2

The other answers don't mention that you can also set this in the XML of your Toolbar widget:

app:navigationIcon="?attr/homeAsUpIndicator"

For example:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:navigationIcon="?attr/homeAsUpIndicator"
    app:popupTheme="@style/AppTheme.PopupOverlay"
    app:title="@string/title_activity_acoustic_progress" />
Michael Litvin
  • 3,976
  • 1
  • 34
  • 40
2

Just sharing something that helped me and may be useful for others. Although most of the answers here are correct, by using the getActionBar().setDisplayHomeAsUpEnabled(true);, this wasn't working for me. The issue I had was that I was trying to create a second Activity manually, but there are more details involved.
What really solved my problem was following Android Developers tutorial (https://developer.android.com/training/basics/firstapp/starting-activity) for creating a second Activity using Android Studio own tools:

Create the second activity
1. In the Project window, right-click the app folder and select New > Activity > Empty Activity.
2. In the Configure Activity window, enter "DisplayMessageActivity" for Activity Name and click Finish (leave all other properties set to the defaults).
Android Studio automatically does three things:
- Creates the DisplayMessageActivity file.
- Creates the corresponding activity_display_message.xml layout file.
- Adds the required <activity> element in AndroidManifest.xml.
ofri cofri
  • 886
  • 10
  • 13
1

If you are using an ActionBar you're going to want to read up on this documentation http://developer.android.com/reference/android/app/ActionBar.html#setDisplayHomeAsUpEnabled(boolean)

Then you have to overwrite the method onOptionsItemSelected(MenuItem) and look for the android.R.id.home event to come in. Then you know the user has clicked on that back button on the actionbar

Paul Thompson
  • 3,290
  • 2
  • 31
  • 39
1

It can also be done without code by specifying a parent activity in app manifest If you want a back button in Activity B which will goto Activity A, just add Activity A as the parent of Activity B in the manifest.

aby4reality
  • 63
  • 1
  • 5
0

You can also simply put onBackPressed() in your onClick listener. This causes your button to act like the default "back/up" buttons in android apps!

user3700215
  • 185
  • 2
  • 10
0
Toolbar toolbar=findViewById(R.id.toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

if (getSupportActionBar()==null){
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
    finish();
return super.onOptionsItemSelected(item);
}
Paul Chu
  • 1,249
  • 3
  • 19
  • 27
0

This is working for me.. Suppose there are two activity (Activityone,Activitytwo)

Inside Activitytwo use this code

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

On Activityone

//when you need to go second activity
startActivity(new Intent(Activityone.this, Activitytwo.class));

This should be included in second activity inside manifest file

<activity android:name=".Activitytwo"
        android:parentActivityName=".Activityone"></activity>

And The result would be like this

enter image description here

Muhaiminur Rahman
  • 3,066
  • 20
  • 27
-1

This is working for me getSupportActionBar().setDisplayHomeAsUpEnabled(false); enter image description here

Minh Vũ
  • 1
  • 3