Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 863
Tamas Koos Avatar asked Dec 15 '22 21:12

Tamas Koos


2 Answers

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.

like image 112
MrEngineer13 Avatar answered Jan 05 '23 09:01

MrEngineer13


You have to override onBackpressed() method and add PARENT_ACTIVITY meta-data in the Manifest file. Here is how to achieve this:

Add the below two lines in the Manifest file.

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

And override the onBackpressed() method in ChildActivity:

 @Override
 public void onBackPressed(){
 NavUtils.navigateUpFromSameTask(this);
 }
like image 38
Sonu Sourav Avatar answered Jan 05 '23 08:01

Sonu Sourav