fragment生命周期思考

通常情况我们都是通过add方法来操作,这样导致容器里的层级比较多,显然效率比replace(只存在一个层级一个fragment)要低,取舍这个视情况而定。

1.通过add方法来添加fragment

每次add的过程其实就是在容器里添加fragment的过程,一般会把fragment添加到回退栈里,每次都会重新走生命周期,每个fragment都是独立的。

activity启动然后add fragment走的生命周期:

FragmentActivity: --------------onCreate

BlankFragmentOne: -----onAttach

-----onCreate

BlankFragmentOne: -----onCreateView

-----onActivityCreated

-----onStart

FragmentActivity: --------------onStart

FragmentActivity: --------------onResume

BlankFragmentOne: -----onResume

添加fragment

getActivity().getSupportFragmentManager().beginTransaction().add(rId, fragment, fragment.getClass().getSimpleName()).addToBackStack(fragment.getClass().getSimpleName()).commitAllowingStateLoss();

生命周期:BlankFragmentOne: -----onAttach -----onCreate -----onCreateView -----onActivityCreated -----onStart  -----onResume

回退生命周期:

如果栈里面有fragment就pop没有说明只有activity直接finish

if (getActivity().getSupportFragmentManager().getBackStackEntryCount() >1) {

    getActivity().getSupportFragmentManager().popBackStack();

} else{

    getActivity().finish();

}

onPause -----onStop  -----onDestroyView-----onDestroy 

2.通过replace方法来添加fragment

从BlankFragmentOne通过replace方法添加fragment,每次都会先将之前的fragmen从容器里清掉,然后通过add方法添加到容器里

getActivity().getSupportFragmentManager().beginTransaction()

.replace(rId, fragment, fragment.getClass().getSimpleName())

.commitAllowingStateLoss();

BlankFragmentTwo: -----onAttach

BlankFragmentTwo: -----onCreate

BlankFragmentOne: -----onPause

BlankFragmentOne: -----onStop

   -----onDestroyView

BlankFragmentOne: -----onDestroy

    -----onDetach

BlankFragmentTwo: -----onCreateView

BlankFragmentTwo: -----onActivityCreated

3.viewpager里添加fragment

如下图:很清楚,activity先显示获取焦点,首先两个fragment都没显示setUserVisibleHint 都为false,然后BlankFragmentOne要显示,所以setUserVisibleHint为true,接着BlankFragmentOne显示走完生命周期,然后BlankFragmentTwo预加载走生命周期。

FragmentActivity: --------------onCreate

FragmentActivity: --------------onStart

FragmentActivity: --------------onResume

BlankFragmentOne: -----setUserVisibleHintfalse

BlankFragmentTwo: -----setUserVisibleHintfalse

BlankFragmentOne: -----setUserVisibleHinttrue

BlankFragmentOne: -----onAttach

    -----onCreate

BlankFragmentTwo: -----onAttach

    -----onCreate

BlankFragmentOne: -----onCreateView

BlankFragmentOne: -----onActivityCreated

    -----onStart

    -----onResume

BlankFragmentTwo: -----onCreateView

BlankFragmentTwo: -----onActivityCreated

BlankFragmentTwo: -----onStart

    -----onResume

两个fragment滑动切换:只走setUserVisibleHint 显示为true,隐藏为false,其他生命周期无关,离开当前页面的时候会调onPause和onStop,返回的时候会调onStart和onResume。 如图:



你可能感兴趣的:(fragment生命周期思考)