Android onConfigurationChanged: how to save and restore fragment back stack?

折月煮酒 提交于 2019-12-05 03:22:13

I was able to do this by caching the Fragments as I added them in my own ArrayList. Then I set up an OnBackStackChangedListener to keep track of which one was shown and pop off the ArrayList as necessary.

My purpose was a little different but the code below should be what you need for what you describe. The tags are so you can have multiple back stacks if you need. It won't compile as-is (I've clipped lots of my own code) but should give you an idea of how I did it. Additional disclaimer: I just got this working and there may be issues I haven't hit yet.

   public void replaceFragmentWithBackStackForTag(Fragment fragment, String tag)
   {
      FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
      ft.detach(visibleFragment);
      ft.add(R.id.realtabcontent, fragment, tag);
      ft.attach(fragment);
      ft.addToBackStack(null);
      manualBackStacks.get(tag).add(fragment);
      ft.commit();
      this.getSupportFragmentManager().executePendingTransactions();
   }

The code you'll want where your activity gets recreated after an orientation change:

 ArrayList<Fragment> backStack =
       new ArrayList<Fragment>(manualBackStacks.get(tag));
 popArrayListToIndex(manualBackStacks.get(tag), 0); // helper I wrote
 for (int bs = 1; bs < backStack.size(); bs++) {
    replaceFragmentWithBackStackForTag(backStack.get(bs), tag);
 }

The backstack listener:

 public void onBackStackChanged() {
    int index = getSupportFragmentManager().getBackStackEntryCount();
    ArrayList<Fragment> backStack = manualBackStacks.get(tag);
    visibleFragment = backStack.get(index);
    // Pop the last element if we've backed up.
    popArrayListToIndex(backStack, index);
 }

Hope this helps.

Action Bar Sherlock (ABS) needed to recreate the action bar as part of recreating the activity in ABS 3.x, but according to @Jake Wharton's comment, version 4 does not need recreation--it can handle orientation changes. So, set android:configChanges="orientation" and your fragment back stack will persist.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!