在两个片段之间切换的最佳方式

GLe*_*Lee 8 android android-fragments

我对能够在两个片段之间切换的单个活动的最佳方式感兴趣.

我已经阅读了15篇关于如何做到这一点的Stack Overflow帖子和5篇博客文章,虽然我认为我拼凑了一个解决方案,但我不相信它是最好的.因此,我希望听到人们对正确处理此问题的看法,特别是关于父活动和片段的生命周期.

以下是详细情况:

  1. 可以显示两个可能片段之一的父活动.
  2. 这两个片段的状态是我希望在会话中持续存在,但不一定需要在会话之间持久化.
  3. 许多其他活动,例如父活动和碎片可能被埋没在后堆栈中并因内存不足而被破坏.
  4. 我希望能够使用后退按钮在片段之间移动(所以我理解它,我不能使用setRetainInstance).

除了一般的架构建议,我还有以下突出问题:

  1. 如果由于内存不足导致父活动被破坏,我如何保证两个片段的状态将被保留,如下文所示:当更换片段并放入后栈(或删除)时,它是否保留在内存中?.我只需要指向父活动中每个片段的指针吗?
  2. 父活动跟踪当前显示的片段的最佳方法是什么?

提前致谢!

GLe*_*Lee 7

我最后使用支持片段管理器添加了两个片段,然后使用detach/attach在它们之间切换.我能够使用commitAllowingStateLoss()因为我在其他地方保留了视图的状态,并在onResume()中手动设置了正确的片段.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.my_layout, new AFragment(), TAG_A);
    fragmentTransaction.add(R.id.my_layout, new BFragment(), TAG_B);
    fragmentTransaction.commit();
}

public void onResume() {
    super.onResume();
    if (this.shouldShowA) {
        switchToA();
    } else {
        switchToB();
    }
}

private void switchToA() {
    AFragment fragA = (AFragment) getSupportFragmentManager().findFragmentByTag(TAG_A);
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.detach(getSupportFragmentManager().findFragmentByTag(TAG_B));
    fragmentTransaction.attach(fragA);
    fragmentTransaction.addToBackStack(null);

    fragmentTransaction.commitAllowingStateLoss();
    getSupportFragmentManager().executePendingTransactions();
}
Run Code Online (Sandbox Code Playgroud)