[java] How to implement the Android ActionBar back button?

I have an activity with a listview. When the user click the item, the item "viewer" opens:

List1.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {

        Intent nextScreen = new Intent(context,ServicesViewActivity.class);
        String[] Service = (String[])List1.getItemAtPosition(arg2);

        //Sending data to another Activity
        nextScreen.putExtra("data", datainfo);
        startActivityForResult(nextScreen,0);
        overridePendingTransition(R.anim.right_enter, R.anim.left_exit);
    }
});

This works fine, but on the actionbar the back arrow next to the app icon doesn't get activated. Am I missing something?

This question is related to java android android-3.0-honeycomb

The answer is


To enable the ActionBar back button you obviously need an ActionBar in your Activity. This is set by the theme you are using. You can set the theme for your Activity in the AndroidManfiest.xml. If you are using e.g the @android:style/Theme.NoTitleBar theme, you don't have an ActionBar. In this case the call to getActionBar() will return null. So make sure you have an ActionBar first.

The next step is to set the android:parentActivityName to the activity you want to navigate if you press the back button. This should be done in the AndroidManifest.xml too.

Now you can enable the back button in the onCreate method of your "child" activity.

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

Now you should implement the logic for the back button. You simply override the onOptionsItemSelected method in your "child" activity and check for the id of the back button which is android.R.id.home.

Now you can fire the method NavUtils.navigateUpFromSameTask(this); BUT if you don't have specified the android:parentActivityName in you AndroidManifest.xml this will crash your app.

Sometimes this is what you want because it is reminding you that you forgot "something". So if you want to prevent this, you can check if your activity has a parent using the getParentActivityIntent() method. If this returns null, you don't have specified the parent.

In this case you can fire the onBackPressed() method that does basically the same as if the user would press the back button on the device. A good implementation that never crashes your app would be:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            if (getParentActivityIntent() == null) {
                Log.i(TAG, "You have forgotten to specify the parentActivityName in the AndroidManifest!");
                onBackPressed();
            } else {
                NavUtils.navigateUpFromSameTask(this);
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Please notice that the animation that the user sees is different between NavUtils.navigateUpFromSameTask(this); and onBackPressed().

It is up to you which road you take, but I found the solution helpful, especially if you use a base class for all of your activities.


Building on Jared's answer, I had to enable and implement the action bar back button behavior in several activities and created this helper class to reduce code duplication.

public final class ActionBarHelper {
    public static void enableBackButton(AppCompatActivity context) {
        if(context == null) return;

        ActionBar actionBar = context.getSupportActionBar();
        if (actionBar == null) return;

        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

Usage in an activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    ActionBarHelper.enableBackButton(this);
}

Make sure your the ActionBar Home Button is enabled in the Activity:

Android, API 5+:

@Override
public void onBackPressed() {
     ...
     super.onBackPressed();
}

ActionBarSherlock and App-Compat, API 7+:

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

Android, API 11+:

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

Example MainActivity that extends ActionBarActivity:

public class MainActivity extends ActionBarActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Back button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home: 
            // API 5+ solution
            onBackPressed();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

This way all the activities you want can have the backpress.

Android, API 16+:

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

AndroidManifest.xml:

<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.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- The meta-data element is needed for versions lower than 4.1 -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

Example MainActivity that extends ActionBarActivity:

public class MainActivity extends ActionBarActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Back button
        getSupportActionBar().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);
    }
}

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

in onCreated method for the new apis.


I think onSupportNavigateUp() is simplest and best way to do so

check the code in this link Click here for complete code


https://stackoverflow.com/a/46903870/4489222

To achieved this, there are 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);}
}

AndroidManifest file:

    <activity android:name=".activity.DetailsActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="br.com.halyson.materialdesign.activity.HomeActivity" />
    </activity>

add in DetailsActivity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);   
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

it's work :]


Android Annotations:

@OptionsItem(android.R.id.home)
void homeSelected() {
    onBackPressed();
}

Source: https://github.com/excilys/androidannotations


If you are using Toolbar, I was facing the same issue. I solved by following these two steps

  1. In the AndroidManifest.xml
<activity android:name=".activity.SecondActivity" android:parentActivityName=".activity.MainActivity"/>
  1. In the SecondActivity, add these...
Toolbar toolbar = findViewById(R.id.second_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Following Steps are much enough to back button:

Step 1: This code should be in Manifest.xml

<activity android:name=".activity.ChildActivity"
        android:parentActivityName=".activity.ParentActivity"
        android:screenOrientation="portrait">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.ParentActivity" /></activity>

Step 2: You won't give

finish();

in your Parent Activity while starting Child Activity.

Step 3: If you need to come back to Parent Activity from Child Activity, Then you just give this code for Child Activity.

startActivity(new Intent(ParentActivity.this, ChildActivity.class));

In the OnCreate method add this:

if (getSupportActionBar() != null)
    {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

Then add this method:

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-3.0-honeycomb

Why fragments, and when to use fragments instead of activities? How to implement the Android ActionBar back button? How to hide action bar before activity is created, and then show it again? Android replace the current fragment with another fragment getActionBar() returns null Fragments onResume from back stack How to set a Fragment tag by code? Android: How to change the ActionBar "Home" Icon to be something other than the app icon? ActionBar text color Unable to resolve host "<insert URL here>" No address associated with hostname