[android] Display back button on action bar

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.

This question is related to android android-actionbar android-homebutton

The answer is


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

Manifest.xml

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

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

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

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

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

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.


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!


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

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"

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

Add below code in the onCreate function:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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


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

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;

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.


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

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.


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

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


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

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


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..!


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

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

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