Save State And Restore State In Fragmentstatepageradapter
Solution 1:
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
).
Solution 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.
Post a Comment for "Save State And Restore State In Fragmentstatepageradapter"