Dynamically set parent activity

Android

Android Problem Overview


So at the moment I have an activity that can be reached from two different activities, the problem is that I can only set one activity as the parent activity in the manifest XML file. Obviously this is bad UX/UI design because the activity may send the user back to the wrong activity they were at previously and so I'm trying to dynamically set which activity is the parent activity.

The trouble is I'm not quite sure how to go about this, whether in code or XML so any pointers are appreciated. :)

Android Solutions


Solution 1 - Android

For future readers here's an example of how to actually implement the official/proper solution as per the developer guides (scroll to the paragraph beginning with "This is appropriate when the parent activity may be different...").

Note that this solution assumes you are using the Support Library to implement your ActionBar and that you can at least set a 'default' parent Activity in your manifest XML file to fallback on if the Activity you are backing out of is in a 'task' that doesn't belong to your app (read the linked docs for clarification).

// Override BOTH getSupportParentActivityIntent() AND getParentActivityIntent() because
// if your device is running on API 11+ it will call the native
// getParentActivityIntent() method instead of the support version.
// The docs do **NOT** make this part clear and it is important!

@Override
public Intent getSupportParentActivityIntent() {
    return getParentActivityIntentImpl();
}

@Override
public Intent getParentActivityIntent() {
    return getParentActivityIntentImpl();
}

private Intent getParentActivityIntentImpl() {
    Intent i = null;
    
    // Here you need to do some logic to determine from which Activity you came.
    // example: you could pass a variable through your Intent extras and check that.
    if (parentIsActivityA) {
        i = new Intent(this, ActivityA.class);
        // set any flags or extras that you need.
        // If you are reusing the previous Activity (i.e. bringing it to the top
        // without re-creating a new instance) set these flags:
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        // if you are re-using the parent Activity you may not need to set any extras
        i.putExtra("someExtra", "whateverYouNeed");
    } else {
        i = new Intent(this, ActivityB.class);
        // same comments as above
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        i.putExtra("someExtra", "whateverYouNeed");
    }

    return i;
}

NOTE: If you do not set a default parent Activity in the manifest XML file then you'll also need to implement onCreateSupportNavigateUpTaskStack() since the system will have no idea how to generate a backstack for your task. I have not provided any example for this part.

My thoughts on the finish() type solutions

On my searching for a solution to this problem I came across a few answers that advocate the strategy of overriding onOptionsItemSelected() and intercepting the android.R.id.home button so they could simply finish() the current Activity to return to the previous screen.

In many cases this will achieve the desired behavior, but I just want to point out that this is definitely not the same as a proper UP navigation. If you were navigating to the child Activity through one of the parent Activities, then yes finish() will return you to the proper previous screen, but what if you entered the child Activity through a notification? In that case finish()ing by hitting the UP button would drop you right back onto the home screen or whatever app you were viewing before you hit the notification, when instead it should have sent you to a proper parent Activity within your app.

Solution 2 - Android

Like this way you can navigate dynamically to your parent activity:

getActionBar().setDisplayHomeAsUpEnabled(true);

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

NOTE: It redirects you to the activity or fragment where you came from, no matter whether it's a parent or not. Clicking on the action bar Up/Home button will just finish the current activity.

Solution 3 - Android

There are two concepts in play here 'Up' and 'Back'. 'Back' is the obvious one: take me to where I was just before I came here. Usually you don't need to be concerned with 'Back', as the system will handle it just fine. 'Up' is not so obvious - it's analogous to Zoom Out - from an element to the collection, from a detail to the wider picture.

Which of these fits your use case?


As per comment below: the up button pulls the destination from the android manifest, but it can be customized programmatically.

Solution 4 - Android

The method to override is getParentActivityIntent.

Here is my code and works perfectly fine.

@Override
public Intent getParentActivityIntent() {
    Intent parentIntent= getIntent();
    String className = parentIntent.getStringExtra("ParentClassSource"); 

    Intent newIntent=null;
    try {
        //you need to define the class with package name
        newIntent = new Intent(OnMap.this, Class.forName(className));

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return newIntent;
}

From the parent activities;

Intent i = new Intent(DataDetailsItem.this, OnMap.class);
i.putExtra("ParentClassSource", "com.package.example.YourParentActivity");
startActivity(i);

Solution 5 - Android

To find out how to use Up Navigation properly see this Android Dev Guide.

Note that there is a big flaw in the above Android Dev Guide as the NavUtils functions work differently for ICS(and lower) and JellyBean(and higher). This flaw in NavUtils is explained beautifully here.

Solution 6 - Android

Generally, a 'detail' type of activity will have to provide the 'up' navigation if it has nested/related contents. The 'back' navigation is handled by the system so you really don't have to worry about it.

Now for the extra effort to support the 'up' navigation, there are a few ways of doing it:

  1. Activity that has the parent activity defined in the AndroidManifest.

     Your Android Manifest
     ---------------------
     
     <activity
     	android:name="com.example.app.DetailActivity"
     	android:parentActivityName="com.example.app.MainActivity" >
     	<meta-data 
     		android:name="android.support.PARENT_ACTIVITY"
     		android:value="com.example.app.MainActivity" />
     </activity>
     
     Your Detail Activity
     --------------------
     
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
     	
     	switch (item.getItemId()) {
     		case android.R.id.home:
     			NavUtils.navigateUpFromSameTask(this);
     			return true;
     	}
     	return super.onOptionsItemSelected(item);
     }
     
    

    This works well if there's only one parent activity meaning if the (DetailActivity) always gets launched from (MainActivity). Otherwise this solution will not work if (DetailActivity) gets launched from different places. More here: http://developer.android.com/training/implementing-navigation/ancestral.html

  2. (Easier and Recommended) Activity with Fragment and Fragment back-stack:

     Your Detail Activity
     --------------------
     
     protected void replaceFragment(Bundle fragmentArguments, boolean addToBackStack) {
    
     	DetailFragment fragment = new DetailFragment();
     	fragment.setArguments(fragmentArguments);
    
     	// get your fragment manager, native/support
     	FragmentTransaction tr = fragmentManager.beginTransaction();
     	tr.replace(containerResId, fragment);
     	if (addToBackStack) {
         	tr.addToBackStack(null);
     	}
     	tr.commit();
     }
     
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
     	
     	switch (item.getItemId()) {
     		case android.R.id.home:
     			finish();
     			return true;
     	}
     	return super.onOptionsItemSelected(item);
     }
     
    

    In this solution, if the user presses 'back', the fragment will be popped from the fragment backstack and the user is taken back to the previous fragment while still remaining in the same activity. If the user presses the 'up', the activity dismisses and the user is lead back to the previous activity (being the parent activity). The key here is to use the Fragment as your UI and the activity as the host of the fragment.

Hope this helps.

Solution 7 - Android

You can override the Up button to act like the back button as following:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

Solution 8 - Android

You will need to keep track of the parent activity. One way to do this is by storing it as an extra in the intent you create to start the child activity). For example, if Activity A starts Activity B, store A's intent in the intent created for B. Then in B's onOptionsItemSelected where you handle the up navigation, retrieve A's intent and start it with the desired intent flags.

The following post has a more complex use-case with a chain of child activites. It explains how you can navigate up to the same or new instance of the parent and finish the intermediate activities while doing so.

https://stackoverflow.com/questions/14654357/android-up-navigation-for-an-activity-with-multiple-parents

Solution 9 - Android

Kotlin 2020

My activity launches from different activities so the AndroidManifest only works with 1 parent activity.

You can return to the previous activity like this:


supportActionBar?.setDisplayHomeAsUpEnabled(true)

override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when(item!!.itemId){
            android.R.id.home -> {
                finish()
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDarryl BaylissView Question on Stackoverflow
Solution 1 - AndroidTony ChanView Answer on Stackoverflow
Solution 2 - AndroidSajView Answer on Stackoverflow
Solution 3 - AndroidTassos BassoukosView Answer on Stackoverflow
Solution 4 - AndroidMichael TarimoView Answer on Stackoverflow
Solution 5 - AndroidkpsfooView Answer on Stackoverflow
Solution 6 - AndroidPirdad SakhizadaView Answer on Stackoverflow
Solution 7 - AndroidHasan El-HefnawyView Answer on Stackoverflow
Solution 8 - Androidrohans310View Answer on Stackoverflow
Solution 9 - AndroidfinalpetsView Answer on Stackoverflow