Tamas Koos Tamas Koos - 1 year ago 224
Android Question

onBackPressed() to parent activity

I have an app with lots of activities. In an activity, I want to go back to the parent activity when I press the back button. (The previous activity and the parent activity are not the same). How can I do this with onBackPressed?
Thanks is advance.

Answer Source

Check out this page about navigation from the documentation. Here's what they have to say:

To navigate up when the user presses the app icon, you can use the NavUtils class's static method, navigateUpFromSameTask(). When you call this method, it finishes the current activity and starts (or resumes) the appropriate parent activity. If the target parent activity is in the task's back stack, it is brought forward. The way it is brought forward depends on whether the parent activity is able to handle an onNewIntent() call:

If the parent activity has launch mode , or the up intent contains FLAG_ACTIVITY_CLEAR_TOP, the parent activity is brought to the top of the stack, and receives the intent through its onNewIntent() method.

If the parent activity has launch mode , and the up intent does not contain FLAG_ACTIVITY_CLEAR_TOP, the parent activity is popped off the stack, and a new instance of that activity is created on top of the stack to receive the intent.


First add the parent activity to the manifest:

<!-- A child of the main activity -->
    android:parentActivityName="com.example.myfirstapp.MainActivity" >
    <!-- Parent activity meta-data to support 4.0 and lower -->
        android:value="com.example.myfirstapp.MainActivity" />

Then call NavUtils.navigateUpFromSameTask(this); when the back button is pressed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download