Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache a fragment view

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

like image 638
Release Avatar asked Jul 02 '12 10:07

Release


1 Answers

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)

like image 75
MariusBudin Avatar answered Oct 20 '22 05:10

MariusBudin