简体   繁体   中英

Controlling Fragment lifecycle using ViewPager

I am using a ViewPager with fragments (i got 4 of them) and I need to make sure that one specific fragment is kept in memory at all times. This is because I have a service that send messages to it.

Because fragments gets destroyed by the ViewPager for memory consumption, I cannot guarantee that this fragment will be in memory.

So, I used viewPager.setOffscreenPageLimit(3) to make sure that ALL my fragments are in memory. Even that is not guarantee to work (i think) because the ViewPager can make an executive decision and destroy some of my fragments at will.

so, my question is, can i control which fragments are always kept in memory and never destroyed, or should i cache the messages and read them on the onCreateView of the specific fragment?

You should definitely use the latter approach: save your messages somewhere, and let the Fragment fetch the data. It's a losing battle trying to control the life cycle of Android's UI objects.

One possible approach is to use Fragments.setArguments when your fragment is constructed, because Android maintains the arguments when the fragment is destroyed and then re-created. Not sure if this will work for ViewPager, but it's a nice solution for rotation.

I would propose another design for your activity.

You could create a headless background fragment (a fragment without UI returning null from onCreateView() ) and make it retained . This will ensure the fragment stays active all the time, even when device is rotated and activity get's re-created. This fragment must receive message from your service and "redistribute" them across all components of your activity. This can be some via standard interface based approach (which is ineffective) or you can use an event bus like TinyBus or EventBus ), which will end up in much less code at the end.

Fragments in your ViewPager will subscribe for events whey are interested in, when they are created by ViewPager . Thus you don't need to keep any UI fragments always created, but just a single background fragment.

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