简体   繁体   English

活动与片段之间的生命周期

[英]Lifecycle between activity and fragment

In my debugging, I notice that onPause/onStart/onStop/onDestroy is called first on the fragment then on its activity, whereas onResume is the opposite - activity's onResume is called first before its fragment. 在调试中,我注意到onPause / onStart / onStop / onDestroy首先在片段上调用,然后在其活动上调用,而onResume相反-活动的onResume在其片段之前首先调用。

Why is the order different for onPause/onStart/onStop vs onResume between activity and fragment? 为什么活动和片段之间onPause / onStart / onStop和onResume的顺序不同?

09-28 15:26:40.869  30320-30320/testintent D/TestFragment﹕ onStart
09-28 15:26:40.869  30320-30320/testintent D/TestActivity﹕ onStart 
09-28 15:26:40.869  30320-30320/testintent D/TestActivity﹕ onResume 
09-28 15:26:40.869  30320-30320/testintent D/TestFragment﹕ onResume 
09-28 15:26:40.869  30320-30320/testintent D/TestActivity﹕ onPostResume

只是在猜测停止时,您从内部到外部组件停止运行,而从外部到内部开始运行。

I have also gone through the below links: 我还浏览了以下链接:

You can refer Activity onStart() being called before Fragment's onActivityCreated() 您可以引用Activity onStart()在Fragment的onActivityCreated()之前调用

http://developer.android.com/guide/components/fragments.html http://developer.android.com/guide/components/fragments.html

在此处输入图片说明

Also it is clearly mentioned in the doc like: The flow of a fragment's lifecycle, as it is affected by its host activity, is illustrated by figure. 在文档中也清楚地提到了它:片段的生命周期流(受其宿主活动影响)用数字表示。

In this figure, you can see how each successive state of the activity determines which callback methods a fragment may receive. 在此图中,您可以看到活动的每个连续状态如何确定片段可以接收的回调方法。 For example, when the activity has received its onCreate() callback, a fragment in the activity receives no more than the onActivityCreated() callback. 例如,当活动收到其onCreate()回调时,该活动中的一个片段接收的内容最多不过是onActivityCreated()回调。

Once the activity reaches the resumed state, you can freely add and remove fragments to the activity. 活动达到恢复状态后,即可自由添加和删除活动片段。 Thus, only while the activity is in the resumed state can the lifecycle of a fragment change independently. 因此,只有在活动处于恢复状态时,片段的生命周期才能独立更改。

However, when the activity leaves the resumed state, the fragment again is pushed through its lifecycle by the activity . 但是, 当活动离开恢复状态时,活动再次将片段推入其生命周期

Hope this helps out. 希望这会有所帮助。

Why is the onResume() order important in your activity/fragment? 为什么onResume()顺序在您的活动/片段中很重要? According to Google guidelines Fragments should be designed as pluggable components without dependency on parent Activity. 根据Google指南,片段应设计为可插入的组件,而不依赖于父活动。

I suspect that you may have too much dependency on your parent activity inside Fragment and may have to refactor. 我怀疑您可能对Fragment内的父活动有过多的依赖,因此可能需要重构。

Ideally Fragments should be designed in such a way that you'll be able to plug it into any activity without any modifications.. 理想情况下,片段的设计方式应使您无需修改​​即可将其插入任何活动。

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

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