简体   繁体   English

使用ViewPager控制片段生命周期

[英]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. 我正在使用带片段的ViewPager(我有4个片段),并且需要确保始终在内存中保留一个特定的片段。 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. 因为片段被ViewPager销毁以消耗内存,所以我不能保证此片段将在内存中。

So, I used viewPager.setOffscreenPageLimit(3) to make sure that ALL my fragments are in memory. 因此,我使用了viewPager.setOffscreenPageLimit(3)来确保所有片段都在内存中。 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. 即使这样也不能保证正常工作(我认为),因为ViewPager可以做出行政决定并随意销毁我的某些片段。

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? 因此,我的问题是,我可以控制哪些片段始终保留在内存中并且永不销毁,还是应该缓存消息并在特定片段的onCreateView上读取它们?

You should definitely use the latter approach: save your messages somewhere, and let the Fragment fetch the data. 您绝对应该使用后一种方法:将消息保存在某个地方,然后让Fragment提取数据。 It's a losing battle trying to control the life cycle of Android's UI objects. 试图控制Android UI对象的生命周期是一场失败的战斗。

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. 一种可能的方法是在构造片段时使用Fragments.setArguments,因为Android在片段被销毁然后重新创建时会保留参数。 Not sure if this will work for ViewPager, but it's a nice solution for rotation. 不知道这是否适用于ViewPager,但这是旋转的一个不错的解决方案。

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 . 您可以创建一个无头的背景片段(一个没有UI从onCreateView()返回null的片段)并将其保留 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. 这可以通过基于标准接口的方法实现 (无效),也可以使用事件总线(如TinyBusEventBus ),最后以更少的代码结束。

Fragments in your ViewPager will subscribe for events whey are interested in, when they are created by ViewPager . ViewPager片段由ViewPager创建时,它们将订阅感兴趣的事件。 Thus you don't need to keep any UI fragments always created, but just a single background fragment. 因此,您不需要始终创建任何UI片段,而只需保留一个背景片段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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