Display back button on action bar
Asked Answered
L

25

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.

Lou answered 28/3, 2013 at 15:59 Comment(1)
Use: getSupportActionBar().setDisplayHomeAsUpEnabled(true);Dett
S
222

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;
Subkingdom answered 23/7, 2013 at 6:8 Comment(4)
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 clickedUno
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.Feinstein
Make sure you set the parent activity in AndroidMenifest.xml for R.id.home button to work.Amphipod
supportActionBar?.setDisplayHomeAsUpEnabled(true) This works for me .Schlessel
H
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.

Hoodwink answered 12/5, 2016 at 11:17 Comment(7)
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.Maui
If you're not using the support library for the Actionbar, modify as follows: getActionBar().setDisplayHomeAsUpEnabled(true); @Override public boolean onNavigateUp(){ finish(); return true; }Lishalishe
Thanks for your help. By using manifest, it was not working but using the code it is workingGuff
i cant return to the hamburguer menu after goin to any fragment.Migratory
@viniciusgati This is the solution for activities as for I know. If you are using fragments you should use trasitionManager.addToBackStack() methodHoodwink
override onOptionsItemSelected instead of onNavigateUpJelsma
@Ssenyonjo why android has built this specific method? its better to use onSupportNavigationUp(). If you don't want to no one will force you.Hoodwink
P
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);
    }
}
Prescott answered 28/3, 2013 at 21:6 Comment(4)
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??Mullinax
You should add getActionBar().setDisplayHomeAsUpEnabled(true); in your onCreateMethod first for show back buttonVersion
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.Swayne
use this.onBackPressed(); method when the user clicks the back button.Transship
C
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

Carisa answered 11/4, 2014 at 17:20 Comment(1)
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.Lucilius
B
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..!

Balliol answered 21/10, 2015 at 6:12 Comment(0)
P
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;
}
Pinhole answered 15/7, 2014 at 20:11 Comment(0)
T
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"
Tamarau answered 3/1, 2015 at 16:52 Comment(1)
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.Posture
O
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);
}
Ourself answered 3/9, 2019 at 20:12 Comment(0)
V
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

Vacua answered 9/2, 2017 at 20:37 Comment(0)
B
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!

Bergin answered 2/7, 2016 at 3:47 Comment(0)
F
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;
}
Farinaceous answered 6/1, 2019 at 8:11 Comment(0)
H
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);
        }
    }
Hesperidium answered 18/8, 2015 at 15:38 Comment(0)
D
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);
}
Dumas answered 24/10, 2017 at 6:47 Comment(0)
M
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.

Medial answered 5/4, 2018 at 11:40 Comment(0)
R
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.

Rentfree answered 26/11, 2020 at 2:0 Comment(0)
B
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();
}
Ballinger answered 15/2, 2017 at 14:39 Comment(0)
P
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);
    }
}
Pittel answered 29/11, 2018 at 6:19 Comment(0)
M
2

Manifest.xml

<activity
            android:name=".Activity.SecondActivity"
            android:label="Second Activity"
            android:parentActivityName=".Activity.MainActivity"
            android:screenOrientation="portrait"></activity>
Moonshine answered 11/3, 2019 at 4:41 Comment(0)
B
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)
 }
Butcherbird answered 12/5, 2020 at 2:42 Comment(0)
M
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);
}
Mantelletta answered 14/10, 2015 at 6:57 Comment(0)
D
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;
}
Dryden answered 5/10, 2017 at 6:0 Comment(0)
D
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);
}
Dobbs answered 5/4, 2018 at 11:29 Comment(0)
V
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;
}
Verlinevermeer answered 4/11, 2018 at 23:18 Comment(0)
S
0

Add below code in the onCreate function:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

Sangraal answered 26/6, 2019 at 15:42 Comment(0)
S
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

Sparhawk answered 9/5, 2020 at 9:17 Comment(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?, some tips and advice about self-promotion, What is the exact definition of "spam" for Stack Overflow?, and What makes something spam.Facelifting

© 2022 - 2024 — McMap. All rights reserved.