简体   繁体   中英

Android activity and fragment lifecycle

This link provide a visualization of the lifecycle for activity and fragment. But it didn't really mention the full lifecycle when fragment is being triggered from an activity. Can someone please explain what is the sequence of method will be triggered (both fragment and activity) when users change the device orientation? Will this be the sequence:

  1. Fragment.onPause,
  2. Fragment.onSaveInstance,
  3. Fragment.onStop,
  4. Fragment.onDestroy,
  5. Activity.onPause,
  6. Activity.onSaveInstance,
  7. Activity.onStop,
  8. Activity.onDestory,
  9. Activity create again ... and running
  10. Fragment create again ... and running

Just created an example and tested for you. I had a PlaceholderFragment attached in MainActivity onCreate.

The call stacks when user change Orientation:

07-09 15:47:59.932: I/System.out(9756): Fragment onPause
07-09 15:47:59.952: I/System.out(9756): Activity onPause
07-09 15:47:59.952: I/System.out(9756): Activity onSaveInstanceState
07-09 15:47:59.952: I/System.out(9756): Fragment onStop
07-09 15:47:59.952: I/System.out(9756): Activity onStop
07-09 15:47:59.952: I/System.out(9756): Fragment onDestroyView
07-09 15:47:59.952: I/System.out(9756): Fragment onDestroy
07-09 15:47:59.952: I/System.out(9756): Fragment onDetach
07-09 15:47:59.972: I/System.out(9756): Activity onDestroy
07-09 15:48:00.072: I/System.out(9756): Fragment onAttach
07-09 15:48:00.072: I/System.out(9756): Fragment onCreate
07-09 15:48:00.172: I/System.out(9756): Activity onCreate
07-09 15:48:00.172: I/System.out(9756): Fragment onCreateView
07-09 15:48:00.172: I/System.out(9756): Fragment onActivityCreated
07-09 15:48:00.172: I/System.out(9756): Fragment onStart
07-09 15:48:00.172: I/System.out(9756): Activity onStart
07-09 15:48:00.182: I/System.out(9756): Activity onResume
07-09 15:48:00.182: I/System.out(9756): Fragment onResume

I have also attached code below in case you want to experiment with it. (Edit: please see previous edit for code)

Also Android Developer guide has good explanation on Activity and 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