23

I'd like to cache a fragment view. My Activity has swipeable tabs and each tab calls a different fragment. But when i swipe between tabs the transition seems a quite slow because of the destruction of the fragment view, that is rebuilded during the swipe operation. Does anyone know how can i cache the view of each fragment to prevent this issue? I work with library support v4 and api 14

I tried to implement a constructor for the fragments, called by the activity container of the fragments: i call the constructor, the fragments are created as variable of the activity class and then, whenever a fragment has to show itself, the activity class returns the fragment object i created before, but this doesn't improve my application a lot because the view of the fragment is destroyed anyway

Release
  • 1,167
  • 1
  • 12
  • 21
  • have you tried caching the view in fragment itself and on the onCreateView you return the cached fragment? Or the view is always destroyed? – ffleandro Oct 25 '12 at 11:13
  • Do you use `ViewPager` for your "swipeable tabs"? – Evos Jan 07 '13 at 07:37

1 Answers1

22

This is because internally by default the pager loads a maximum of 3 pages (fragments) at the time: the one displaying, previous and next so if you have 5 fragments this will happen while you move from first to last: (where x is a loaded fragment)

xx000 -> xxx00 -> 0xxx0 -> 00xxx -> 000xx

Try using

myPager.setOffscreenPageLimit(ITEMS_COUNT-1);

This will tell the pager to keep all of them in memory and not destroy/create with every swipe (keep a close look on the memory management)

MariusBudin
  • 1,277
  • 1
  • 10
  • 21
  • 1
    Won't this call `onCreateView` of a tab fragment? (Where the fragment layout view is loaded) – StarDust Feb 28 '13 at 05:49
  • 1
    @StarDust yes, this will call onCreateView for all the fragments at the same time at the beginning.It's tricky, you can run out of memory or simply will get a black screen or block because of the fragment loading process. This solution is nice if you have to load 4 or 5 light fragments but I wouldn't do it for 10 heavy-loading fragments. You can set the offscreenPageLimit to any number lower than your fragments count, for example if you have 10 pages and set the limit to 4 and you are in the 6th screen, it will load 2 extra in both directions like this 000xx **x** xx00 (best solution I think) – MariusBudin Feb 28 '13 at 10:22