Reputation: 35
I have viewPager with adapter where I instantiate fragment and return it in getItem() method. So when Im on the first page I have only 2 fragments alive. When I rotate the phone, they both get destroyed and garbage collected (system calls their onDestroy() and onDetach() and I can see them in .hprof memory dump as ready to be garbage collected). However, when a new activity is created with new viewpager and 2 new fragments, for some reason, system creates 2 more fragments for those that were destroyed previously and attaches them to the activity, while not adding them to viewPager at all. They just sit in fragmentManager's mActive and mAdded arrays. When I rotate device few times, it creates these new instances each time. Now, this may seem like a leak that causes fragments not to be garbage collected but they indeed are. All these fragments have different @xxx number and are atached to a new activity within a new fragment manager. I've tried everything, any help or suggestions are much appreciated, thanks!
Upvotes: 0
Views: 94
Reputation: 35
So I it was (unexpectedly:D) bad code. I had in my Activity's onRestoreInstanceState() piece of code that was creating and setting new adapter and so it put old fragments in background. Sorry for bothering with unanswerable question.
Upvotes: 0
Reputation: 5589
ViewPager handles the lifecycle of the Fragments it shows. As you mention it creates the visible Fragment and the ones next to it (if used with a FragmentStatePagerAdapter
) to be able to smoothly swipe into them when the time comes. When the fragment is out of sight, it can be destoryed and recreated by the ViewPager
at its will.
The default beheavior for a rotating screen is that the activity is recreated together with the ViewPager
and the Fragments
.
However this can be changed.
With android:configChanges="orientation"
in the manifest you can prevent the activity of being recreated upon orientation change.
The other way of preserving the fragment instance upon an orientation change is to call setRetainInstance(true)
in the fragment to be retained.
Upvotes: 1