Fragment与Activity的联动

Fragment和Activity完整的生命周期如图所示。

image.png

下面给出Activity与Fragment联动时的执行顺序。

  1. 当Fragment在Activity的onCreate()中被添加时
    • Activity super.onCreate执行完毕
      • Fragment onAttach
      • Fragment onCreate
      • Fragment onCreateView
      • Fragment onViewCreated
    • Activity.super.onStart()执行中
      • Fragment onActivityCreated
      • Fragment onViewStateRestored
      • Fragment onStart()
    • Activity super.onStart执行完毕
    • Activity super.onPostCreate()
    • Activity super.onResume()
    • Activity super.onPostResume()执行中
      • Fragment onResume()
    • Activity super.onPosResume()执行完毕
    • Activity onAttachedToWindow()
    • Activity onCreateOptionsMenu()
      • Fragment onCreateOptionsMenu()
    • Activity onPrepareOptionsMenu()
      • Fragment onPrepareOptionsMenu()
    • Activity onWindowFocusChanged()
  2. 暂停生命周期
    • Activity super.onPause()执行中
      • Fragment.onPause()
    • Activity super.onPause()执行完毕
    • Activity super.onSaveInstanceState()执行中
      • Fragment onSaveInstanceState()
    • Activity super.onSaveInstanceState()执行完毕
    • Activity super.onStop()执行中
      • Fragment onStop()
    • Activity super.onStop()执行完毕
  3. 销毁的生命周期
    • Activity super.onDestroy()执行中
      • Fragment onDestroyView()
      • Fragment onDestroy()
      • Fragment onDetach()
    • Activity super.onDestroy()执行完毕
  4. 重启的生命周期
    • Activity super.onRestart()
    • Activity super.onStart()执行中
      • Fragment onStart()
    • Activity super.onStart()执行完毕
    • Activity super.onResume()
    • Activity super.onPostResume()执行中
      • Fragment onResume()
    • Activity super.onPosResume()执行完毕
    • Activity onWindowFocusChanged()执行完毕