39

我在使用此导航树在应用程序上实现向上导航时遇到问题:

应用导航树

后退按钮的标准实现很好。

当尝试实现向上按钮时,问题就开始了。

我的期望:

  • 当用户在Detail 5 Activity上并按下向上按钮时,应用程序会转到List 3 Activity
  • 当用户在Detail 7 Activity上并按下向上按钮时,应用程序将返回Home Activity

因此,在不同的方面,我希望在后堆栈上有这种行为:

应用程序后台清除

Android 文档(实现祖先导航)建议使用以下代码来处理导航

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

但是由于Detail Activity的父 Activity在不同的导航路径上有所不同,我不知道它到底是哪一个。所以我不能在意图中调用它。

有没有办法知道 Android 后台堆栈中真正的父活动?

如果没有,有没有办法在这个应用程序中实现正确的向上导航

4

3 回答 3

22

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 (:

于 2013-02-01T22:52:55.253 回答
2

这是一个棘手的问题,在我看来,这确实表明了应对 Android 的“向上按钮”用户体验决策的困难。因此,您的问题没有明确的答案。

我有两个可能的解决方案给你。

1.模仿后退按钮的行为。

您可以考虑在意图中添加一个额外的内容,以便从其不同的父项之一启动Detail 。这个额外的信息会通知那些活动他们在android.R.id.home按下时需要启动哪些活动。

这实际上意味着您的应用程序“回到”它的共同祖先,而不是简单地重新启动Home

另一种实现方式可能是简单地执行onBackPressed()而不是使用 启动HomeIntent.FLAG_ACTIVITY_CLEAR_TOP但请记住,关联的动画将不同于正常的“向上”动作。

2.跳过中间活动,回家。

一些应用程序将“向上按钮”视为“主页按钮”。您可能要考虑让它始终使用Intent.FLAG_ACTIVITY_CLEAR_TOP.

于 2013-02-01T20:38:18.570 回答
0

这肯定是一篇旧文章,但是当我研究 SharedPreferences 时,我认为有可能将此信息堆叠在 sharedPreferences 数据中,并在每次访问 2 个父母之前修改其值。然后通过阅读它,您应该能够直接了解您的父母,而无需为此建立一个完整的班级。

于 2016-11-17T15:49:42.373 回答