how to override action bar back button in android?
Asked Answered
S

10

103

I want to customize the activity back button in action bar, not in hard key back button. I have overriden the onBackPressed() method. It works with my emulator back button, but not with action bar back button.

I want it to happen with action bar. How can I do this?

Here is my code:

@Override
public void onBackPressed() {
    Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show(); 
    return;
}

I have used this toast whether back pressed is working or not but the actual implementation changes like to move back to previous activity. But this is not working with the button present on top of action bar (besides title of the activity).

Please any one could specify me the problem.

Staphylo answered 21/1, 2013 at 11:34 Comment(0)
D
226

I think you want to override the click operation of home button. You can override this functionality like this in your activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show(); 
        break;
    }
    return true;
}
Danielledaniels answered 21/1, 2013 at 11:38 Comment(5)
Noah Ibrahim, Actually there is Back button on Top left corner like back button in browser. When I click on that button, I want to go back to previous activity. Not like the code u posted above.Staphylo
add super.onBackPressed(); to itBacchic
This worked for me after I changed return true; to return super.onOptionsItemSelected(item). Then you can make something happen when the user clicks the actionbar back button, but still retain the same functionality of the button.Mimimimic
By this technique the back arrow button is responding late. Means i have to wait for a second to get event fired. Also not appearing the selector on this button for the effect while pressing itEtiquette
Didn't work for me. When I debugged, I found the ids of home button and the id of button clicked different.Rechabite
W
51

If you want ActionBar back button behave same way as hardware back button:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == android.R.id.home) {
                    onBackPressed();
                    return true;
            }
            return false;
    }
Wales answered 6/1, 2015 at 22:2 Comment(2)
case android.R.id.home does not firingRumba
@Rumba if you use it in Fragment, you should additionally call setHasOptionsMenu(true) in fragment's onCreate methodMaas
D
11

Two things to keep in mind that the user can either press back button or press the actionbar home button.
So, if you want to redirect him to the same destination then you can do this.

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

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
    startActivity(intent);
    finish();
}

This will take the user to the intent pressing either key or the action bar button.

Discomfort answered 13/8, 2015 at 16:14 Comment(3)
case android.R.id.home does not firingRumba
@Trancer, It has almost been 1.5+ years. And I don't do android now. I can't help you now. Sorry.Discomfort
so what's the solution?Halifax
B
10

Sorry mine is a late answer, but for anyone else arriving at this page with the same question, I had tried the above:

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

but this failed to catch the "Back" button press.

Eventually I found a method that worked for me on https://mcmap.net/q/126708/-display-back-button-on-action-bar which is to override the "onSupportNavigateUp()" as I am using the actionbar from the "AppCompatActivity" support library. (There is an equivalent "onNavigateUp()" for the newer actionbar/toolbar library.)

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

and I removed the "android:parentActivityName=".MainActivity" section from the manifest file.

Bombazine answered 11/6, 2018 at 10:24 Comment(0)
T
7
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                case android.R.id.home:
                       finish();
                   break;
                }
                return true;
        }
Teshatesla answered 7/2, 2014 at 7:49 Comment(1)
You could have added it as a comment. It's more or less the same as the accepted answer.Potty
I
6

(1) Add Parent activity for your child activity (AndroidManifest.xml)

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

(2) override the onSupportNavigateUp method inside the child activity

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return false;
}
Iraqi answered 22/3, 2020 at 18:16 Comment(0)
F
4

I have achieved this, by using simply two steps,

Step 1: Go to AndroidManifest.xml and in the add the parameter in 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);
 }
Feininger answered 24/10, 2017 at 6:58 Comment(0)
D
2

If you want to return to the previous instance of an Activity by pressing of ActionBar home button, without recreating it, you can override getParentActivityIntent method to use the one from the back stack:

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public Intent getParentActivityIntent() {
      return super.getParentActivityIntent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}

EDIT:
Also you can achieve the same result by
setting the launchMode of your parent activity to singleTop.
So setandroid:launchMode="singleTop" to parent activity in your manifest.
Or you can use flag FLAG_ACTIVITY_CLEAR_TOP with the UP intent.
reference: Providing Up Navigation

Disenthrone answered 15/3, 2016 at 8:55 Comment(0)
A
0
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == android.R.id.home) {
        onBackPressed();
        return true;
    }
    //noinspection SimplifiableIfStatement
    if (id == R.id.signIn) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
///////////////////
@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}
Astyanax answered 19/10, 2017 at 12:3 Comment(0)
B
0

There are several ways how to set up back button in bar:

1) method .setDisplayHomeAsUpEnabled(true); will do it, and then you can simply override android.R.id.home

2) adding <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="my.package.parrent" /> in Android Manifest, but in this case you can not override android.R.id.home in OnOptionsMenuSelected.

.. for those who wonder why it doesn't work for them...

Bleach answered 2/2, 2018 at 13:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.