Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

Android up navigation for an Activity with multiple parents

I have a problem for implementing up navigation on an app with this navigation tree:

App navigation tree

The standard implementation of the back button is fine.

The problem start when trying to implement the Up button.

What I expect:

  • when the user is on Detail 5 Activity and press the up button the app goes to List 3 Activity
  • when the user is on Detail 7 Activity and press the up button the app goes back to Home Activity

So in different terms, I'd like to have this behaviour on the back stack:

app backstack clear

The Android documentation (Implementing Ancestral Navigation) advice to use the following code to handle up navigation:

Intent parentActivityIntent = new Intent(this, MyParentActivity.class);
parentActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(parentActivityIntent);
finish();

But because the parent activity of the Detail Activity differs on the different navigation path I don't know which one it really is. So I can't call it in the Intent.

Is there a way to know the real parent activity in the Android back stack?

If not, is there a way to implement a correct up navigation in this app?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I will stick with my comment on Paul's answer:

The idea is to have a Stack of the last Parent Activities traversed. Example:

public static Stack<Class<?>> parents = new Stack<Class<?>>();

Now in all your parent activities (the activities that are considered parents -e.g. in your case: List and Home), you add this to their onCreate:

protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     parents.push(getClass()); 
     //or better yet parents.push(getIntent()); as @jpardogo pointed
     //of course change the other codes to make use of the Intent saved.

     //... rest of your code
}

When you want to return to the Parent activity, you can use the following (according to your code):

Intent parentActivityIntent = new Intent(this, parents.pop());
parentActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(parentActivityIntent);
finish();

I hope am right (:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...