登录  /  注册
首页 > Java > java教程 > 正文

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

高洛峰
发布: 2017-01-07 16:09:16
原创
1281人浏览过

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

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

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

onAttach(Activity);  //当Activity与Fragment发生关联时调用
 
onCreateView(LayoutInflater,ViewGroup,Bundle);  //创建该Fragment的视图
 
onActivityCreate(bundle);  //当Activity的onCreate();方法返回时调用
 
onDestoryView();  //与onCreateView相对应,当改Fragment被移除时调用
 
onDetach();  //与onAttach()相对应,当Fragment与Activity的关联被取消时调用
登录后复制

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

场景演示 :

切换到该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
登录后复制

屏幕解锁

11-29 14:33:13.240: D/AppListFragment(7649): onStart
11-29 14:33:13.275: D/AppListFragment(7649): onResume
登录后复制

切换到其他Fragment:

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:

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
登录后复制

回到桌面

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
登录后复制

   

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

更多Android中Fragment与Activity的生命周期对比相关文章请关注PHP中文网!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号