Fragment --replace方法和hide、show方法的生命周期分析

总结:1、replace,加回退栈,Fragment不销毁,但是切换回销毁视图和重新创建视图。

          2、replace,不加回退栈,Fragment销毁掉。

          3、hide、show,Fragment不销毁,也不销毁视图。隐藏和显示不走生命周期。


1、Fragment采取replace方法替换、并加入回退栈。

private void replaceFragment(int containerID, Fragment fragment) {
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    transaction.replace(containerID, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

1.1开始的生命周期。

Fragment --replace方法和hide、show方法的生命周期分析

Fragment --replace方法和hide、show方法的生命周期分析

Fragment --replace方法和hide、show方法的生命周期分析

1.2、replace后的生命周期:

可以看到,先执行新的BlankFragment的生命周期到onCreate后,接着执行旧的ItemFragment的生命周期,

从onPause->onStop->onDestroyView.然后在去执行新的BlankFragment的onCreateView方法以及其后的方法一直到onPause。

这样可知,其实并没有销毁Fragment,只是销毁Fragment的视图。

Fragment --replace方法和hide、show方法的生命周期分析

Fragment --replace方法和hide、show方法的生命周期分析

Fragment --replace方法和hide、show方法的生命周期分析

Fragment --replace方法和hide、show方法的生命周期分析

1.3、在看看replace回来后的生命周期。现在BlankFragment为前台旧Fragment。

先销毁BlankFragment的视图

Fragment --replace方法和hide、show方法的生命周期分析

然后接着执行后台ItemFragment创建视图的生命周期:onCreateView一直到onRsume

Fragment --replace方法和hide、show方法的生命周期分析

Fragment --replace方法和hide、show方法的生命周期分析

2、replace方法替换Fragment,不加回退栈

  private void replaceFragment(int containerID, Fragment fragment) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(containerID, fragment);
//        transaction.addToBackStack(null);
        transaction.commit();
    }

2.1 、新起的Fragment 和 1.1一样的。

2.2、前台Fragment给replace后的生命周期。

可以看到,先执行新的BlankFragment的生命周期都onCreate后,再执行旧的ItemFragment的onPause->onStop->onDestroyView->onDestroy-onDetach,销毁了ItemFragment。

Fragment --replace方法和hide、show方法的生命周期分析

Fragment --replace方法和hide、show方法的生命周期分析

Fragment --replace方法和hide、show方法的生命周期分析

Fragment --replace方法和hide、show方法的生命周期分析

2.3、再replace回来重复2.2,只是BlankFragment和ItemFragment互换位置而已。

可见,没加回退栈的Fragment,用replace替换后Fragment都是销毁重新创建的。加了回退栈的,只是销毁视图重新创建视图。


3、Fragment 用hide、show方法。

private void switchFragment(int containerID, Fragment fragment) {
    if (currentFragment != fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (fragment.isAdded()) {
            transaction.hide(currentFragment).show(fragment).commit();
        } else {
            transaction.hide(currentFragment).add(containerID, fragment).commit();
        }
        currentFragment = fragment;
    }
}

这里就不贴生命周期了。因为都只是新创建时候执行从onAttach到onResum。再切换,没有生命周期回调。竟然也没看到onPause回调?再onPause里断点debug也没进断点!!!


总结:1、replace,加回退栈,Fragment不销毁,但是切换回销毁视图和重新创建视图。

          2、replace,不加回退栈,Fragment销毁掉。

          3、hide、show,Fragment不销毁,也不销毁视图。隐藏和显示不走生命周期。