Android Reorder Fragment Backstack

寵の児 提交于 2019-11-27 13:14:06

There is no API to do this, but becuse I was wondering the same thing last week,
I took it as an exercise an implemented it myself.

My method allows you to remove a Fragment from anywhere in the backstack and this is achieved by using refrection to modify the internal variables that store the backstack information in FragmentManagerImpl and BackStackRecord.

There are few important variables:

  • mBackStack - stores the BackStackRecords that hold the Fragment info, the previous ones, animations, etc
  • mActive - all added Fragments
  • mAvailBackStackIndices - stores the indices that can be used by the newly inserted records, i.e. indices of null values in mActive
  • and other

Tested with 150+ Fragments and couldn't notice any leaks, but only monitored the heap in DDMS and did not perform any other memory analysis.
So because someting may be broken, explore the code, re-test it, see if anyone provides a better answer, and rethink if you really need to do this in your project.

I uploaded the code as a gist on GitHub, hope it helps.

When you want to reuse the fragment before it, just first hide all the fragments and show the desired fragment at a time. By doing this you can reuse your fragments without removing them and without reloading the fragments. But be sure before to implement it you have to add the fragment to backstack.

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