How to cache a fragment view

梦想的初衷 提交于 2020-01-01 01:13:09

问题


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


回答1:


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)



来源:https://stackoverflow.com/questions/11291739/how-to-cache-a-fragment-view

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