android - 如何为具有多个 fragment 的 Activity 弹出堆栈?

标签 android android-fragments

Activity layout picture

假设我有一个 Activity,其中包含两个 FrameLayout(我们称它们为 FrameA 和 FrameB),而 每个 又包含一个 Fragment(我们分别称它们为 FragmentA1 和 FragmentB1)。现在,我使用类似于以下的代码提交一系列单独的 fragment 事务...

getFragmentManager()
 .beginTransaction()
 .replace(frameId, fragment)
 .addToBackStack(null)
 .commit();

...这样我将FrameA中的FragmentA1替换为FragmentA2,然后将FrameB中的FragmentB1替换为FragmentB2,然后将FrameA中的FragmentA2替换为FragmentA3,然后将Frame2中的FragmentB2替换为FragmentB3,最终状态看起来像上图(只有 FragmentA3 和 FragmentB3 可见)。

如果我正确理解后退堆栈的工作原理,按“后退”将在 FrameA 和 FrameB 之间交错弹出 fragment (反射(reflect)我添加它们的方式)。

有谁知道是否可以选择性地弹出 FrameA 或 FrameB 上的最后一个事务? (即,如果我按下“Pop FrameA”,那么 FrameA 将从 FragmentA3 转换回 FragmentA2,相反,如果我按下“Pop FrameB”,那么 FrameB 将从 FragmentB3 转换回 FragmentB2)

Supplement: I know I can get the Fragment last added to a given FrameLayout using the FragmentManager.findFragmentById(int framelayoutId) method, but calling FragmentTransaction.remove(fragment).commit() only removes the Fragment from the View and does not transition the View back to the Fragment it previously displayed.

最佳答案

基本上,没有,一个 Activity 只有一个回栈。

您只需要实现自己的独立后退栈。

从 Android 4.0(和相关的支持库)开始,有一些 API 可以让这变得相对简单 -- FragmentTransaction.detach(Fragment)允许您将 fragment 置于与在后堆栈中时相同的状态,以及 FragmentManager.saveFragmentInstanceState(Fragment)让你走得更远,彻底扔掉 Fragment 对象。并非巧合,它们分别用于实现 ViewPager 的 FragmentPagerAdapter 和 FragmentStatePagerAdapter,因此您可以查看它们的代码作为如何使用它们的示例。

关于android - 如何为具有多个 fragment 的 Activity 弹出堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8772921/

相关文章:

android - AlarmManager 正在阻塞主线程

android - Google分析跟踪器的创建未给出enableAdvertisingIdCollection(true)的结果

java - 设置结果不工作

安卓 fragment 动画

android - fragment 与 FragmentActivity

android - 为什么服务 Intent 需要显式 Intent

java - 如何在android中设置一个主要 Activity 并填充 fragment

android - 如何将项目从 gridview 拖放到另一个布局中

android - Android SDK 中 FetchedAppGateKeepersManager 中的 Facebook 错误崩溃

android - 异步任务后更新 ListFragment