简体   繁体   中英

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.

Why is the order different for onPause/onStart/onStop vs onResume between activity and fragment?

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()

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.

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? According to Google guidelines Fragments should be designed as pluggable components without dependency on parent Activity.

I suspect that you may have too much dependency on your parent activity inside Fragment and may have to refactor.

Ideally Fragments should be designed in such a way that you'll be able to plug it into any activity without any modifications..

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