0
点赞
收藏
分享

微信扫一扫

Fragment生命周期

陆佃 2021-10-09 阅读 94
随笔

Fragment的生命周期函数流程如下:

onAttach()---->onCreate---->onCreateView----->onActivityCreated--->onstart---->onResume--->onPause---->onStop------->onDestroyView------>onDestroy----->onDetach

onAttach---》在Fragment和Activity建立关联时调用(Activity传递到此方法内)
onCreateView---->当Fragment创建视图时调用
onActivityCreated----->在相关联的Activity的onCreate方法已返回时调用
onDestroyView----->当Fragment视图被移除时调用
onDetach---->在Fragment与Activity取消关联时调用

以下几种情况看下Fragment的生命周期变化:

1、打开页面:onCreate-->onCreateView--->onActivityCreated--->onStart---->onResume
2、按下主屏幕键(home键):onPause--->onStop
3、重新打开页面:onStart--->onResume
4、按下返回键:onPause---->onStop---->onDestroyView--->onDestroy---->onDetach

当Activity加入Fragment,Activity与Fragment的生命周期变化是:

1、打开页面
Fragment  onCreate--->Fragment   onCreateView---->Activity  onCreate--->Fragment  onActivityCreated--->Activity onStart----> Fragment  onStart ----->  Activity  onResume--->Fragment  onResume
2、按下home键
Fragment  onpause  ---->Activity  onPause---->Fragment  onStop  ---->Activity onStop
3、重新打开页面
Activity onRestart---->Activity  onStart --->Fragment  onStart---->Activity onResume--->Fragment  onResume
4、按后退键
Fragment onPause---->Activity  onPause---->Fragment  onStop ---->Activity  onStop ----->Fragment onDestroyView---->Fragment onDestroy---->Fragment  onDetach ---->Activity onDestroy

Fragment 生命周期与 Activity 生命周期的一个关键区别就在于,Fragment 的生命周期方法是由托管Activity而不是操作系统调用的。Activity 中生命周期方法都是 protected,而 Fragment 都是 public,也能印证了这一点,因为 Activity 需要调用 Fragment 那些方法并管理它。






onAttach ---->onCreate---->onCreateView ---->onActivityCreated-->onstart-->onResume-->onPause-->onStop--->onDestroyView---->onDestroy----->onDetach

举报

相关推荐

0 条评论