Proper way to handle action bar up button?

Have you also tried this (taken from Android website here) :

in the manifest, for each activity X that needs to go to the main activity, add this to the code:

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

and this to its manifest xml tag:

<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.activities.MainActivity" />

if you need to still have the same state on the main activity, use this code instead :

Intent intent = NavUtils.getParentActivityIntent(this); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP); 
NavUtils.navigateUpTo(this, intent);

if the API is 16 or above, you can add an attribute of parentActivityName with the path to the main activity instead of the metadata .

Leave a Comment