Save State and Restore State in FragmentStatePagerAdapter
Asked Answered
P

2

7

I a using ViewPager with FragmentStatePageAdapter on my screen I have 5 pages which has lots of images and views. Currently I have mViewPager.setOffscreenPageLimit(1); so only current, previous and next will be in memory and other 2 will be destroyed. But for that destroyed fragments I want to make use of saveState() and restoreState() of the adapter to maintain its state so when I come back to that screen it will anyways go to onCreateView() of that fragment what will maintain state also.

Having mViewPager.setOffscreenPageLimit(4); is not a good option as it has memory issues.

I searched a lot but I didn't get any sample which make use of this 2 functions to maintain and restore state.

Can someone help me out to proceed.

Pause answered 7/5, 2013 at 9:56 Comment(0)
I
3

There is NO need to override saveState() and restoreState() methods of FragmentStatePagerAdapter.

Mainly because it is the core of FragmentStatePagerAdapter implementation that was already done for you. The FragmentManager that you pass to the constructor takes care of restoring the fragments that were previously instantiated. Actually, instantiateItem() callback of the FragmentStatePagerAdapter makes sure it returns fragments with their saved state.

With that said, just override onSaveInstanceState() method of your fragment and put everything you want to be restored into a Bundle outState.

The data you place in the Bundle will be available in the Bundle given to onCreate(Bundle), onCreateView(LayoutInflater, ViewGroup, Bundle), and onActivityCreated(Bundle) methods.

By now you can argue:

"But I have already tried to save the state of the fragment that way. It does not work for me!"

If you find yourself in that situation, check how you initialize your state variables of the fragments. It may be that you are getting what you want from the Bundle, but then override it from values you get from getArguments() method of the fragment. (which was exactly my struggle and probably your case also, if you are using factory method to instantiate the fragments).

Also, put your FragmentStatePagerAdapter in the onCreate method of the activity (and not into onStart).

Idyllist answered 20/6, 2017 at 8:48 Comment(0)
A
2

FragmentStatePageAdapter takes care of it's state see: FragmentStatePagerAdapter.java

The best way to go is to remove images (eg. from adapter) in onDestroyView callback and reload them in onCreatView. Fragments and adapters would restore their state accordingly.

The only catch is that you should not create FragmentStatePagerAdapter every time in onStart because it will not be aware of saved state.

Aleron answered 11/12, 2013 at 15:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.