前言:Android系统运行在各种各样的设备中,有小屏幕手机,有大屏的平板甚至电视。针对屏幕尺寸的差距,很多情况下,都是先针对于手机开发一套APP,然后拷贝一份,修改布局,以此来适应大屏设备。有没有什么办法可以同时适应手机和平板呢?那就是Fragment。Fragment 出现的初衷就是为了解决这样的问题。
1Fragment的文字解释
Fragment必须是依存于Activity而存在的。
因此,Activity的生命周期会直接影响到Fragment的生命周期。
onAttach()
onCreate()
onCreateView()
onActivityCreated()
onStart()
onResume()
onPause()
onStop()
onDestroyView()
onDestroy()
onDetach()
可以看到Fragment比Activity多了几个生命周期
onAttach(Activity); //当Activity与Fragment发生关联时调用
onCreateView(LayoutInflater,ViewGroup,Byndle); //创建该Fragment的视图
onActivityCreate(bundle); //当Activity的onCreate();方法返回时调用。
onDestroyView(bundle); //与onCreateView相对应,当该Fragment被移除时调用
onDetach(); //与onAttach相对应,当Fragment与Activity的关联被取消时调用。
注意:除了onCreateView,其他所有的方法如果你重写了,必须要调用父类对于该方法的实现。
2图解Fragment的生命周期
3Activity与Fragment生命周期对比
4Frangment在代码中的体现
场景演示 : 切换到该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
4总结
Fragment在使用中很少单独出现,我们一般都是Activity和Fragment的组合使用,不仅如此,在ViewPager的使用中,更是把Fragment发挥到了极致!
欢迎大家关注微信公众号进行技术交流和提出意见,我一定会最快回复你!