25

I have an application that calls an activity several times from different activitys. So, im trying to implement the "back button" in the action bar for this activity. For doing this im using:

 switch (item.getItemId()) {
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    default:        
         return super.onOptionsItemSelected(item);
    }

and:

<meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="view.TweetsIndividuoActivity" />

The problem now, is that i cannt set a parent activity to my android manifest, cause, i don't know who is the parent of this activity.

What is the solution ?

Thanks

3 Answers3

43

It's easier than you think.

switch (item.getItemId()) {
    case android.R.id.home:
        finish();
        return true;
    default:        
         return super.onOptionsItemSelected(item);
}

Method finish() will destroy your activity and show the one that started it. That's what you want if I understood you right.

Your current solution is meant for cases when you want go back to the same parent every time e.g. Gmail app does it. When you open email from notification and then press actionbar back button it will not navigate back to HOME screen but it will show you Gmail inbox.

Damian Petla
  • 8,963
  • 5
  • 44
  • 47
  • 2
    Thanks ! But if this way, works, i don't understand why to use: NavUtils.navigateUpFromSameTask(this); – Redes ConnectedGroup May 05 '14 at 18:07
  • 2
    It's meant for what I wrote in the last part of my answer. Activities are running in tasks. If you open an activity that belongs to another task you have to options: 1. go back to previously visible activity; that's what back button does 2. go back to previous activity on the current task. Read http://developer.android.com/guide/components/tasks-and-back-stack.html for detailed explanation. – Damian Petla May 05 '14 at 21:03
  • Ughhh I got caught up by someone using a shiny Google Util (NavUtils.navigateUpFromSameTask(this);)... – DoctorD May 31 '17 at 20:48
10
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        onBackPressed();
        return  true;
    }
    return super.onOptionsItemSelected(item);

}

You will always go back to the activity from which you have launched the new activity.

No need to use the code below.

<meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="view.TweetsIndividuoActivity" />
Pranav Anand
  • 467
  • 6
  • 12
1

I'm a newbie to Android too, but I solved this problem by calling the 2nd activity using "startActivityForResult(intent,1)" instead of "startActivity(intent)". I think this makes it a parent/child relationship instead of a sibling activity...?

I didn't need to use onOptionsItemSelected() or finish().

Tim Cooper
  • 10,023
  • 5
  • 61
  • 77