理解Fragment的生命周期

本文详细解析了Fragment在不同场景下的生命周期变化,包括与Activity生命周期的区别、屏幕锁定解锁、Fragment之间的切换等,并通过具体日志展示了各个生命周期方法的调用顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Fragment的生命周期


          


二、与Activity的生命周期做对比


     


三、场景演示 


切换到该Fragment:

11-29 14:26:35.095: D/AppListFragment(7649): onAttach
11-29 14:26:35.095: D/AppListFragment(7649): onCreate
11-29 14:26:35.095: D/AppListFragment(7649): onCreateView
11-29 14:26:35.100: D/AppListFragment(7649): onActivityCreated
11-29 14:26:35.120: D/AppListFragment(7649): onStart
11-29 14:26:35.120: D/AppListFragment(7649): onResume


屏幕灭掉:

11-29 14:27:35.185: D/AppListFragment(7649): onPause
11-29 14:27:35.205: D/AppListFragment(7649): onSaveInstanceState
11-29 14:27:35.205: D/AppListFragment(7649): onStop

      PS:onSaveInstanceState()是一个用于保存数据的方法,属于Fragment生命周期中的onPause环节。


屏幕解锁:

11-29 14:33:13.240: D/AppListFragment(7649): onStart
11-29 14:33:13.275: D/AppListFragment(7649): onResume


切换到其他Fragment(在替换Fragment的时候,有调用addToBackStack()方法):

11-29 14:33:20.555: D/AppListFragment(7649): onPause
11-29 14:33:20.555: D/AppListFragment(7649): onStop
11-29 14:33:20.560: D/AppListFragment(7649): onDestroyView


切换回原来的Fragment(调用过addToBackStack()方法):

11-29 14:33:31.715: D/AppListFragment(7649): onActivityCreated
11-29 14:33:31.715: D/AppListFragment(7649): onStart
11-29 14:33:31.715: D/AppListFragment(7649): onResume

      注意此时onCreate()和onCreateView()方法并不会执行,因为我们借助了addToBackStack()方法使得RightFragment和它的视图并没有销毁。


切换到其他Fragment(没有调用addToBackStack()方法,即按返回键无法切换回原来的Fragment):

11-29 14:33:55.655: D/AppListFragment(7649): onPause
11-29 14:33:55.655: D/AppListFragment(7649): onStop
11-29 14:33:55.660: D/AppListFragment(7649): onDestroyView

11-29 14:33:55.660: D/AppListFragment(7649): onDestroy
11-29 14:33:55.660: D/AppListFragment(7649): onDetach


回到桌面:

11-29 14:34:26.590: D/AppListFragment(7649): onPause
11-29 14:34:26.880: D/AppListFragment(7649): onSaveInstanceState
11-29 14:34:26.880: D/AppListFragment(7649): onStop


回到应用:

11-29 14:36:51.940: D/AppListFragment(7649): onStart
11-29 14:36:51.940: D/AppListFragment(7649): onResume


退出应用:

11-29 14:37:03.020: D/AppListFragment(7649): onPause
11-29 14:37:03.155: D/AppListFragment(7649): onStop
11-29 14:37:03.155: D/AppListFragment(7649): onDestroyView
11-29 14:37:03.165: D/AppListFragment(7649): onDestroy
11-29 14:37:03.165: D/AppListFragment(7649): onDetach



本文声明:非原创,转自他人博客,对原文做了部分修改

原文作者:forever_crying(优快云博客作者)
原文链接:http://blog.youkuaiyun.com/forever_crying/article/details/8238863


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值