简体   繁体   English

Viewpager,活动娱乐的片段生命周期

[英]Viewpager, fragment lifecycle on activity recreation

I have a FragmentActivity with a ViewPager instance that uses a FragmentPagerAdapter. 我有一个使用FragmentPagerAdapter的ViewPager实例的FragmentActivity。 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. 我知道在活动的onCreate中,将基于在捆绑中传递的FragmentState实例,首先重新创建片段。 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? 避免在onCreate方法中重新创建片段是否可以接受? 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. 让片段重新创建是一种常见的做法,但是在特定情况下,您可能需要使用Fragment.setRetainInstance() ,但是通常来说,让UI重新创建是可以的。 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. 这就是为什么理想情况下将模型放在UI类之外的原因(例如,Activity,Fragments),因为您可以轻松地重新创建先前的状态。

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

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