Android中Fragment与Activity的生命周期对比

时间:2022-04-07 22:07:02

fragment必须是依存于activity而存在的,因此activity的生命周期会直接影响到fragment的生命周期。官网这张图很好的说明了俩者的关系:

Android中Fragment与Activity的生命周期对比

可以看到fragment比activity多了几个额外的生命周期回调函数:

?
1
2
3
4
5
6
7
8
9
onattach(activity);  //当activity与fragment发生关联时调用
 
oncreateview(layoutinflater,viewgroup,bundle);  //创建该fragment的视图
 
onactivitycreate(bundle);  //当activity的oncreate();方法返回时调用
 
ondestoryview();  //与oncreateview相对应,当改fragment被移除时调用
 
ondetach();  //与onattach()相对应,当fragment与activity的关联被取消时调用

注意:除了oncreateview,其他的所有方法如果你重写了,必须调用父类对于该方法的实现。

场景演示 :

切换到该fragment

?
1
2
3
4
5
6
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

屏幕灭掉:

?
1
2
3
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

屏幕解锁

?
1
2
11-29 14:33:13.240: d/applistfragment(7649): onstart
11-29 14:33:13.275: d/applistfragment(7649): onresume

切换到其他fragment:

?
1
2
3
11-29 14:33:33.655: d/applistfragment(7649): onpause
11-29 14:33:33.655: d/applistfragment(7649): onstop
11-29 14:33:33.660: d/applistfragment(7649): ondestroyview

切换回本身的fragment:

?
1
2
3
4
11-29 14:33:55.820: d/applistfragment(7649): oncreateview
11-29 14:33:55.825: d/applistfragment(7649): onactivitycreated
11-29 14:33:55.825: d/applistfragment(7649): onstart
11-29 14:33:55.825: d/applistfragment(7649): onresume

回到桌面

?
1
2
3
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

回到应用

?
1
2
11-29 14:36:51.940: d/applistfragment(7649): onstart
11-29 14:36:51.940: d/applistfragment(7649): onresume

退出应用

?
1
2
3
4
5
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

比activity多了一些生命周期,完整和activity对接上,大家好好利用。