【问题标题】:How to make the up-button go back to a parent activity on the back stack?如何使向上按钮返回到后堆栈上的父活动?
【发布时间】:2013-01-17 11:48:28
【问题描述】:

我想为向上按钮实现以下行为:

  • 如果父 Activity 的实例在后栈中,则返回到该父 Activity 的最顶层实例。
  • 如果后栈中没有父Activity的实例,则新建一个实例。

实际上,当我第一次阅读 up 和 back 之间的区别时,这种行为是我所期望的默认行为。然而,我现在已经看到,NavUtils.navigateUpFromSameTask(this); 总是创建父活动的一个新实例,而忽略了一个事实,即在后台堆栈上有一个现成可用的实例。

感谢您的建议。

【问题讨论】:

    标签: android navigation android-actionbar


    【解决方案1】:

    尝试在 Manifest android:launchMode="singleInstance" 或 android:launchMode="singleTop" 中为您的活动指定启动模式,请查看此问题以获取更多信息Android launchmode="singleTask" does not work as expected

    【讨论】:

      【解决方案2】:

      如果父 Activity 的实例在后栈中,则返回该父 Activity 的最顶层实例。

      如果这是为了清除返回堆栈到这个最顶层的实例,我最近解决了这个问题,使用活动的onOptionsItemSelected() 自定义向上导航并将FLAG_ACTIVITY_CLEAR_TOP-flag (link) 添加到Intent - 虽然只切换启动模式并没有最终出现在我期待的后台堆栈中:

      @Override
      public boolean onOptionsItemSelected(MenuItem menuItem) {
          Intent parentActivityIntent = NavUtils.getParentActivityIntent(this);
          parentActivityIntent.setFlags(FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(parentActivityIntent);
      }
      

      也可以看看http://developer.android.com/training/implementing-navigation/ancestral.html#NavigateUp

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-28
        • 1970-01-01
        相关资源
        最近更新 更多