Tamas Koos Tamas Koos - 3 months ago 32
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

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.

EDIT:

First add the parent activity to the manifest:

<!-- 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" >
    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.myfirstapp.MainActivity" />
</activity>

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

Comments