首页 > 系统 > Android > 正文

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

2020-04-11 10:44:42
字体:
来源:转载
供稿:网友

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

2016225115117535.jpg (373×684)

可以看到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): onAttach11-29 14:26:35.095: D/AppListFragment(7649): onCreate11-29 14:26:35.095: D/AppListFragment(7649): onCreateView11-29 14:26:35.100: D/AppListFragment(7649): onActivityCreated11-29 14:26:35.120: D/AppListFragment(7649): onStart11-29 14:26:35.120: D/AppListFragment(7649): onResume

屏幕灭掉:

11-29 14:27:35.185: D/AppListFragment(7649): onPause11-29 14:27:35.205: D/AppListFragment(7649): onSaveInstanceState11-29 14:27:35.205: D/AppListFragment(7649): onStop

屏幕解锁

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

切换到其他Fragment:

11-29 14:33:33.655: D/AppListFragment(7649): onPause11-29 14:33:33.655: D/AppListFragment(7649): onStop11-29 14:33:33.660: D/AppListFragment(7649): onDestroyView

切换回本身的Fragment:

11-29 14:33:55.820: D/AppListFragment(7649): onCreateView11-29 14:33:55.825: D/AppListFragment(7649): onActivityCreated11-29 14:33:55.825: D/AppListFragment(7649): onStart11-29 14:33:55.825: D/AppListFragment(7649): onResume

回到桌面

11-29 14:34:26.590: D/AppListFragment(7649): onPause11-29 14:34:26.880: D/AppListFragment(7649): onSaveInstanceState11-29 14:34:26.880: D/AppListFragment(7649): onStop

回到应用

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

退出应用

11-29 14:37:03.020: D/AppListFragment(7649): onPause11-29 14:37:03.155: D/AppListFragment(7649): onStop11-29 14:37:03.155: D/AppListFragment(7649): onDestroyView11-29 14:37:03.165: D/AppListFragment(7649): onDestroy11-29 14:37:03.165: D/AppListFragment(7649): onDetach

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表