简体   繁体   中英

Viewpager, fragment lifecycle on activity recreation

I have a FragmentActivity with a ViewPager instance that uses a FragmentPagerAdapter. I create a list of fragments instances first, and then pass it to the adapter so it can return the right fragment for the right page.

My question now is how to handle Activity recreation. Suppose the app is stopped, in the background the activity is destroyed, and lateron the activity is resumed. I know in onCreate of the activity will recreate fragments first, based on the FragmentState instances it was passed in the bundle. Then a set of other fragments is created and passed to the adapter, which is of course not what I want.

What is the common practice here? Is it acceptable/possible to avoid recreating the fragments in the onCreate method? Or should I try to reuse the recreated fragments and pass them to the adapter?

It's a common practice to let the fragments be recreated, but on specific cases you might want to use the Fragment.setRetainInstance() , but in general, it is OK to let the UI be re-created. Trying to play with that, or try to prevent destroying the activity upon rotation might lead to undesired behavior sometimes making the app over complicated.

That is why, ideally you put the model outside of the UI classes (eg Activity, Fragments) because you can easily recreate the previous state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM