Save State and Restore State in FragmentStatePagerAdapter

风格不统一 提交于 2019-12-03 15:01:30

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).

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.

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