205

I'm trying to display a Back button on the Action bar to move previous page/activity or to the main page (first opening). And I can not do it.

my code.

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

the code is in onCreate.

Shihab Uddin
  • 6,699
  • 2
  • 59
  • 74
Dany Maor
  • 2,391
  • 2
  • 18
  • 26

25 Answers25

221

well this is simple one to show back button

actionBar.setDisplayHomeAsUpEnabled(true);

and then you can custom the back event at onOptionsItemSelected

case android.R.id.home:
this.finish();
return true;
fhamicode
  • 2,498
  • 1
  • 12
  • 7
  • i added the above lines inside the on onOptionsItemSelected(MenuItem item) , since i already have a menu on the action bad am listing the ids to redirect the menu options, the home id doesnt work when clicked –  May 22 '14 at 10:27
  • If you experience weird behavior (as in: you use the back button (R.id.home) of a fragment and end up closing the activity), make sure you do NOT have "android:noHistory" set on this activity, because if you do, even going back from a fragment to the "overview" of the activity will finish it. – Igor Jan 31 '16 at 20:25
  • 4
    Make sure you set the parent activity in AndroidMenifest.xml for R.id.home button to work. – Leap Hawk Oct 26 '16 at 14:32
  • supportActionBar?.setDisplayHomeAsUpEnabled(true) This works for me . – Mayuresh Deshmukh Jan 04 '23 at 09:23
221

I think onSupportNavigateUp() is the best and Easiest way to do so, check the below steps. Step 1 is necessary, step two have alternative.

Step 1 showing back button: Add this line in onCreate() method to show back button.

assert getSupportActionBar() != null;   //null check
getSupportActionBar().setDisplayHomeAsUpEnabled(true);   //show back button

Step 2 implementation of back click: Override this method

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

thats it you are done
OR Step 2 Alternative: You can add meta to the activity in manifest file as

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

Edit: If you are not using AppCompat Activity then do not use support word, you can use

getActionBar().setDisplayHomeAsUpEnabled(true); // In `OnCreate();`

// And override this method
@Override 
public boolean onNavigateUp() { 
     finish(); 
     return true; 
}

Thanks to @atariguy for comment.

Inzimam Tariq IT
  • 6,548
  • 8
  • 42
  • 69
  • 2
    This solution works great when you need to sent data back to the parent activity or if you want to preserve EditText's values in the parent activity. I tried `onOptionsItemSelected` solutions but failed to do so. – weeix Sep 20 '16 at 16:44
  • 4
    If you're not using the support library for the Actionbar, modify as follows: `getActionBar().setDisplayHomeAsUpEnabled(true);` `@Override public boolean onNavigateUp(){ finish(); return true; }` – atariguy Aug 22 '17 at 16:34
  • 1
    Thanks for your help. By using manifest, it was not working but using the code it is working – santosh devnath Sep 18 '18 at 13:06
  • i cant return to the hamburguer menu after goin to any fragment. – vinicius gati Apr 26 '19 at 14:26
  • 1
    @viniciusgati This is the solution for activities as for I know. If you are using fragments you should use trasitionManager.addToBackStack() method – Inzimam Tariq IT Apr 27 '19 at 06:07
  • override onOptionsItemSelected instead of onNavigateUp – Gilbert Jan 09 '21 at 22:45
  • @Ssenyonjo why android has built this specific method? its better to use onSupportNavigationUp(). If you don't want to no one will force you. – Inzimam Tariq IT Jan 12 '21 at 11:44
74

The magic happens in onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; go home
            Intent intent = new Intent(this, HomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
Matthias Robbers
  • 15,689
  • 6
  • 63
  • 73
  • 1
    In my case, I want to add back button in that page where onOptionsItemSelected(MenuItem item) event will not be there...Is there any other solution for that?? – Vidhi Feb 23 '15 at 08:01
  • 1
    You should add `getActionBar().setDisplayHomeAsUpEnabled(true);` in your onCreateMethod first for show back button – aletede91 Mar 27 '15 at 16:06
  • 1
    I think if you do this way, you don't go back even if you start previous activity again having now one instace of it more and you go always forward and forward until stack overflow happens if you continua long enough. I think Igor's answer is correct you should stop this activity with finish() and let framework get you back to previous activity instance running. – Reijo Korhonen Jul 17 '16 at 21:57
  • 2
    use `this.onBackPressed();` method when the user clicks the back button. – CaptRisky Aug 09 '16 at 13:43
46

Official solution

Add those two code snippets to your SubActivity

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

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

add meta-data and parentActivity to manifest to support lower sdk.

 <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.SubActivity"
        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>

Reference here:http://developer.android.com/training/implementing-navigation/ancestral.html

hoot
  • 1,215
  • 14
  • 15
  • 6
    Note: if using support libraries for backwards compatability, you will need to use "getSupportActionBar()" instead of "getActionBar()". This is the most complete, and official, answer. – Christopher Bull Sep 12 '16 at 09:39
34

Add these lines to onCreate()

android.support.v7.app.ActionBar actionBar = getSupportActionBar();
   actionBar.setHomeButtonEnabled(true);
   actionBar.setDisplayHomeAsUpEnabled(true);

and in onOptionItemSelected

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                //Write your logic here
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

Hope this will help you..!

Abhishek
  • 2,295
  • 24
  • 28
29

Try this code, considers it only if you need the back button.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //YOUR CODE
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //YOUR CODE
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return true;
}
Jaime
  • 471
  • 5
  • 6
17

On your onCreate method add:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

While defining in the AndroidManifest.xml the parent activity (the activity that will be called once the back button in the action bar is pressed):

In your <activity> definition on the Manifest, add the line:

android:parentActivityName="com.example.activities.MyParentActivity"
Bruno Peres
  • 2,980
  • 1
  • 21
  • 19
  • You only need to put the Manifest code in if you're looking to support pre-4.0 devices. The first bit of code is a better solution for the current libraries though. – Louie Bertoncin Jun 08 '15 at 20:13
10

In your onCreate() method add this line

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and, in the same Activity, add this method to handle the button click

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        this.finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
Marcel Bro
  • 4,907
  • 4
  • 43
  • 70
Khubaib Raza
  • 543
  • 6
  • 10
8

I know I'm a bit late, but was able to fix this issue by following the docs directly.

Add the meta-data tag to AndroidManifest.xml (so the system knows)

 <activity
        android:name=".Sub"
        android:label="Sub-Activity"
        android:parentActivityName=".MainChooser"
        android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".MainChooser" />
    </activity>

Next, enable the back (up) button in your MainActivity

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_child);
 
    // my_child_toolbar is defined in the layout file 
    Toolbar myChildToolbar =
        (Toolbar) findViewById(R.id.my_child_toolbar);
    setSupportActionBar(myChildToolbar);
 
    // Get a support ActionBar corresponding to this toolbar 
    ActionBar ab = getSupportActionBar();
 
    // Enable the Up button 
    ab.setDisplayHomeAsUpEnabled(true);
    } 

And, you will be all set up!

Source: Android Developer Documentation

Community
  • 1
  • 1
A P
  • 2,131
  • 2
  • 24
  • 36
7

I know that the above are many helpful solutions, but this time I read this article (current Android Studio 2.1.2 with sdk 23) some method above doesn't work.

Below is my solution for sub-activity is MapsActivity

First, you need to add parentActivity in

AndroidManifest.xml

like this :

<application ... >
    ...
    <!-- Main activity (which has no parent activity) -->
    <activity
        android:name="com.example.myapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        .....
        android:parentActivityName=".MainActivity" >
        <!-- Support Parent activity for Android 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myapp.MainActivity" />
    </activity>
</application>

Second, ensure that your sub-Activity extends AppCompatActivity, not FragmentActivity.

Third, override onOptionsItemSelected() method

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon action bar is clicked; go to parent activity
                this.finish();
                return true;
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

Hope this will help!

postace
  • 79
  • 1
  • 6
5

This is simple and works for me very well

add this inside onCreate() method

getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

add this outside oncreate() method

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return true;
}
Muhaiminur Rahman
  • 3,066
  • 20
  • 27
4

Try this, In your onCreate()

 getActionBar().setHomeButtonEnabled(true);
 getActionBar().setDisplayHomeAsUpEnabled(true);

And for clickevent,

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; goto parent activity.
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
Melbourne Lopes
  • 4,817
  • 2
  • 34
  • 36
4

To achieve this, there are simply two steps,

Step 1: Go to AndroidManifest.xml and add this parameter in the <activity> tag - android:parentActivityName=".home.HomeActivity"

Example:

<activity
    android:name=".home.ActivityDetail"
    android:parentActivityName=".home.HomeActivity"
    android:screenOrientation="portrait" />

Step 2: In ActivityDetail add your action for previous page/activity

Example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
    }
    return super.onOptionsItemSelected(item);
}
Xpleria
  • 5,472
  • 5
  • 52
  • 66
Vivek Hande
  • 929
  • 9
  • 11
4

in onCreate method write-

Toolbar toolbar = findViewById(R.id.tool);
    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
}
@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}
@Override
public void onBackPressed() {
    super.onBackPressed();
    startActivity(new Intent(ActivityOne.this, ActivityTwo.class));
    finish();
}

and this is the xml file-

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
android:id="@+id/tool">

and in styles.xml change it to

Theme.AppCompat.Light.NoActionBar

this is all what we have to do.

Pawan Lakhotia
  • 385
  • 1
  • 10
3

In my case; I just had to add android:parentActivityName attr to my activity like this:

<activity
 android:name=".AboutActivity"
 android:label="@string/title_activity_about"
 android:parentActivityName=".MainActivity" />

and the back button appears and works as expected.

Inam Ul Huq
  • 732
  • 7
  • 8
2

I Solved in this way

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

@Override
public void onBackPressed(){
    Intent backMainTest = new Intent(this,MainTest.class);
    startActivity(backMainTest);
    finish();
}
Ardit
  • 168
  • 1
  • 5
2

In oncreate(); write this line->

getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

then implement below method in that class

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
    case android.R.id.home:
        // app icon in action bar clicked; go home
      onBackPressed();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}
Manthan Patel
  • 1,784
  • 19
  • 23
2

Manifest.xml

<activity
            android:name=".Activity.SecondActivity"
            android:label="Second Activity"
            android:parentActivityName=".Activity.MainActivity"
            android:screenOrientation="portrait"></activity>
2

In Order to display action bar back button in Kotlin there are 2 way to implement it

1. using the default Action Bar provided by Android - Your activity must use a theme that has Action Bar - eg: Theme.AppCompat.Light.DarkActionBar

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val actionBar = supportActionBar
    actionBar!!.title = "your title"
    actionBar.setDisplayHomeAsUpEnabled(true)
    //actionBar.setDisplayHomeAsUpEnabled(true)
}

override fun onSupportNavigateUp(): Boolean {
    onBackPressed()
    return true
}

2. Design your own Action Bar - disable default Action Bar - eg: Theme.AppCompat.Light.NoActionBar - add layout to your activity.xml

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

     <androidx.constraintlayout.widget.ConstraintLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         tools:layout_editor_absoluteX="16dp">

         <TextView
             android:id="@+id/main_toolbar_title"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="Your Title"
             android:textSize="25sp"
             app:layout_constraintBottom_toBottomOf="parent"
             app:layout_constraintEnd_toEndOf="parent"
             app:layout_constraintHorizontal_bias="0.5"
             app:layout_constraintStart_toStartOf="parent"
             app:layout_constraintTop_toTopOf="parent" />

     </androidx.constraintlayout.widget.ConstraintLayout>
 </androidx.appcompat.widget.Toolbar>

  • onCreate
override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)

     setSupportActionBar(findViewById(R.id.main_toolbar))
 }
  • create your own button
<?xml version="1.0" encoding="utf-8"?>
<menu
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto" >

 <item
     android:id="@+id/main_action_toolbar"
     android:icon="@drawable/ic_main_toolbar_item"
     android:title="find"
     android:layout_width="80dp"
     android:layout_height="35dp"
     app:actionLayout="@layout/toolbar_item"
     app:showAsAction="always"/>

</menu>
  • in YourActivity.kt
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
     menuInflater.inflate(R.menu.main_toolbar_item, menu)

     leftToolbarItems = menu!!.findItem(R.id.main_action_toolbar)
     val actionView = leftToolbarItems.actionView
     val badgeTextView = actionView.findViewById<TextView>(R.id.main_action_toolbar_badge)
     badgeTextView.visibility = View.GONE

     actionView.setOnClickListener {
         println("click on tool bar")
     }
     return super.onCreateOptionsMenu(menu)
 }
Chea Sambath
  • 1,305
  • 2
  • 13
  • 16
1

my working code to go back screen.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

    case android.R.id.home:

        Toast.makeText(getApplicationContext(), "Home Clicked",
                Toast.LENGTH_LONG).show();

        // go to previous activity
        onBackPressed();

        return true;

    }

    return super.onOptionsItemSelected(item);
}
Shihab Uddin
  • 6,699
  • 2
  • 59
  • 74
1
 public void initToolbar(){
       //this set back button 
       getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       //this is set custom image to back button
       getSupportActionBar().setHomeAsUpIndicator(R.drawable.back_btn_image);
}


//this method call when you press back button
@Override
public boolean onSupportNavigateUp(){
    finish();
    return true;
}
pruthwiraj.kadam
  • 1,033
  • 10
  • 11
1
ActionBar actionBar=getActionBar();

actionBar.setDisplayHomeAsUpEnabled(true);

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

    return super.onOptionsItemSelected(item);
}
akshay shetty
  • 194
  • 3
  • 10
1

It could be too late to answer but I have a shorter and more functional solution in my opinion.

// Inside your onCreate method, add these.
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);

// After the method's closing bracket, add the following method exactly as it is and voiulla, a fully functional back arrow appears at the action bar
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return true;
}
Jan Ndungu
  • 175
  • 1
  • 3
  • 11
0

Add below code in the onCreate function:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

And then override: @Override public boolean onOptionsItemSelected(MenuItem item){ onBackPressed(); return true; }

Hieu.Gi
  • 77
  • 6
0

In updated version getActionBar() does not work!

Instead, you can do this by this way

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

add back button in android title bar this helps you in 2020

  • 1
    Your last couple of answers both link to the same site. Are you associated/affiliated with that site in any way? If you are affiliated, you *must disclose that affiliation in the post*. If you don't disclose affiliation, it's considered spam. See: [**What signifies "Good" self promotion?**](//meta.stackexchange.com/q/182212), [some tips and advice about self-promotion](/help/promotion), [What is the exact definition of "spam" for Stack Overflow?](//meta.stackoverflow.com/q/260638), and [What makes something spam](//meta.stackexchange.com/a/58035). – Makyen May 09 '20 at 12:24