Activity onCreate中直接调用两次add,生命周期如下 FragmentTwo会赶上FragmentOne的生命周期同步
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.linear, fragmentOne);
fragmentTransaction.commit();
FragmentManager fragmentManager1 = getSupportFragmentManager();
FragmentTransaction fragmentTransaction1 = fragmentManager1.beginTransaction();
fragmentTransaction1.replace(R.id.linear, fragmentwo);
fragmentTransaction1.commit();
fragmentone ==== onAttach
fragmentone ==== oncreate
fragmentone ==== onCreateView
fragmentone==== onActivityCreated
FragmentTwo ==== onAttach
FragmentTwo ==== onCreate
FragmentTwo ==== onCreateView
FragmentTwo ==== onActivityCreated
fragmentone ==== onStart
FragmentTwo ==== onStart
fragmentone ==== onResume
FragmentTwo ==== onResume
replace FragmentTwo 通过replace添加 ,FragmentOne不会调用onPause方法,直接调用onDestroyView方法,
fragmentone==== onAttach
fragmentone==== oncreate
fragmentone==== onCreateView
fragmentone==== onActivityCreated
FragmentTwo==== onAttach
FragmentTwo==== onCreate
fragmentone==== onDestroyView
fragmentone==== onDestroy
FragmentTwo==== onCreateView
FragmentTwo==== onActivityCreated
FragmentTwo==== onStart
FragmentTwo==== onResume
第二种情况,onCreate 调用一次commit,然后通过Button点击Onclick ,add的形式生命周期,FragmentTwo会正常走自己的生命周期,FragmentOne生命周期无变化
fragmentone==== onAttach
fragmentone==== oncreate
fragmentone==== onCreateView
fragmentone==== onActivityCreated
fragmentone==== onStart
fragmentone==== onResume
FragmentTwo==== onAttach
FragmentTwo==== onCreate
FragmentTwo==== onCreateView
FragmentTwo==== onActivityCreated
FragmentTwo==== onStart
FragmentTwo==== onResume
按返回键activity直接退出,生命周期
fragmentone==== onPause
FragmentTwo==== onPause
fragmentone==== onStop
FragmentTwo==== onStop
fragmentone==== onDestroyView
fragmentone==== onDestroy
FragmentTwo==== onDestroyView
FragmentTwo==== onDestroy
replace情况的生命周期,FragmentTwo 会先走它的onAttch和onCreate方法,然后FragmentOne调用自己的OnPause后的生命周期方法,FragmentTwo在执行OnCreateView等方法
fragmentone==== onAttach
fragmentone==== oncreate
fragmentone==== onCreateView
fragmentone==== onActivityCreated
fragmentone==== onStart
fragmentone==== onResume
FragmentTwo==== onAttach
FragmentTwo==== onCreate
fragmentone==== onPause
fragmentone==== onStop
fragmentone==== onDestroyView
fragmentone==== onDestroy
FragmentTwo==== onCreateView
FragmentTwo==== onActivityCreated
FragmentTwo==== onStart
FragmentTwo====onResume
总结 replace的情况,FragmentTwo的onAttach和oncCreate 总会比FragmentOne的onPause方法先执行,与Activity启动的对比情况,ActivityA启动ActivityB一定是A先onPause 然后B在执行onCreate方法
在add和hide/show的情况下,切换Fragment A不会调用任何生命周期,只因为Fragment A 的hide 和 show 调用了 onHiddenChanged方法,所有View都一直保存在内存中