Saving Fragment State In Viewpager
Solution 1:
Use ViewPager.setOffscreenPageLimit()
in FragmentActivity
ViewPagerpager= (ViewPager) findViewById(R.id.viewPager);
pager.setOffscreenPageLimit(2);
See more at How do I tell my custom FragmentPagerAdapter to stop destroying my fragments?
Solution 2:
just override this method in FragmentpagerAdapter
@OverridepublicvoiddestroyItem(ViewGroup container, int position, Objectobject) {
// TODO Auto-generated method stubsuper.destroyItem(ViewGroup container, int position, Objectobject);
}
remove super.destroyItem(ViewGroup container, int position, Object object);
from your code
Solution 3:
Update: In the getItem of MyAdapter you return a new instance of your Fragment. Android will not call getItem on every swipe. It will only call getItem to get a new instance, but will reuse the existing instances as long as they are availible.
About the state part of the Demo. I can't help you. I think the normal techniques for restoring state in Fragements/Activities apply here, so nothing special when loading it in a ViewPager (but I might be wrong).
Solution 4:
If you override
publicvoid destroyItem(View container, int position, Objectobject)
without calling super, the fragment will not be destroyed and will be reused.
Solution 5:
The adapter should be extended from FragmentStatePagerAdapter instead of FragmentPageAdapter and the adapter will keep reference from position to fragment item. On the activity or fragment parent, set listener OnPageChangeListener for PageIndicator to detect the position of fragment item has been activated and update related data's state.
About the data state of fragment item, I think should save/restore state from Activity or Fragement parent.
The adapter can add some code as following:
publicstaticclassMyAdapterextendsFragmentStatePagerAdapter {
privateSparseArray<TestFragment> mPageReferenceMap
= newSparseArray<TestFragment>();
...
@OverridepublicObjectinstantiateItem(ViewGroup viewGroup, int position) {
Object obj = super.instantiateItem(viewGroup, position);
//Add the reference when fragment has been create or restoreif (obj instanceofTestFragment) {
TestFragment f= (TestFragment)obj;
mPageReferenceMap.put(position, f);
}
return obj;
}
@OverridepublicvoiddestroyItem(ViewGroup container, int position, Objectobject) {
//Remove the reference when destroy it
mPageReferenceMap.remove(position);
super.destroyItem(container, position, object);
}
publicTestFragmentgetFragment(int key) {
return mPageReferenceMap.get(key);
}
...
}
Hope this help.
Post a Comment for "Saving Fragment State In Viewpager"