Android - Back button in the title bar

AndroidUser InterfaceThemesTitlebar

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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

Solution 3 - Android

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

Solution 4 - Android

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.

Solution 5 - Android

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

Solution 6 - Android

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

Solution 7 - Android

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

Solution 8 - Android

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.

Solution 9 - Android

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

Solution 10 - Android

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

Solution 11 - Android

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.

Solution 12 - Android

The simplest way and best practice as google explains [in here](https://developer.android.com/training/implementing-navigation/ancestral.html "developer.android.com") :

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.

Solution 13 - Android

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 !

Solution 14 - Android

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

Solution 15 - Android

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.

Solution 16 - Android

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.

Solution 17 - Android

For kotlin :

   override fun onOptionsItemSelected(item: MenuItem): Boolean {
        onBackPressed();
        return true;
    }

Solution 18 - Android

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().

Solution 19 - Android

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" />

Solution 20 - Android

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.

Solution 21 - Android

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

Solution 22 - Android

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.

Solution 23 - Android

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!

Solution 24 - Android

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

Solution 25 - Android

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

Solution 26 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDrewView Question on Stackoverflow
Solution 1 - AndroidLukeView Answer on Stackoverflow
Solution 2 - Androidanupam sharmaView Answer on Stackoverflow
Solution 3 - AndroidLucy FairView Answer on Stackoverflow
Solution 4 - AndroidspacebikerView Answer on Stackoverflow
Solution 5 - AndroidtotView Answer on Stackoverflow
Solution 6 - AndroidShahriar AhmadView Answer on Stackoverflow
Solution 7 - AndroidM AneesView Answer on Stackoverflow
Solution 8 - AndroidRuzinView Answer on Stackoverflow
Solution 9 - AndroidMimu Saha TishanView Answer on Stackoverflow
Solution 10 - AndroidS.AdikaramView Answer on Stackoverflow
Solution 11 - AndroidralphgabbView Answer on Stackoverflow
Solution 12 - Androidluke8800gtsView Answer on Stackoverflow
Solution 13 - AndroidZharView Answer on Stackoverflow
Solution 14 - AndroidAhmed AbdullahView Answer on Stackoverflow
Solution 15 - AndroidMygodView Answer on Stackoverflow
Solution 16 - AndroidMuhammad RaqibView Answer on Stackoverflow
Solution 17 - AndroidRaluca LucaciView Answer on Stackoverflow
Solution 18 - AndroidGi TavaresView Answer on Stackoverflow
Solution 19 - AndroidMichael LitvinView Answer on Stackoverflow
Solution 20 - Androidofri cofriView Answer on Stackoverflow
Solution 21 - AndroidPaul ThompsonView Answer on Stackoverflow
Solution 22 - Androidaby4realityView Answer on Stackoverflow
Solution 23 - Androiduser3700215View Answer on Stackoverflow
Solution 24 - AndroidAbhay AgrawalView Answer on Stackoverflow
Solution 25 - AndroidMuhaiminur RahmanView Answer on Stackoverflow
Solution 26 - AndroidMinh VũView Answer on Stackoverflow