Android-Fragment生命周期

Fragment生命周期

最近做Setting,遇到了这样一个应用场景:
1、MainActivity的布局中有一个空的FrameLayout用来显示所有的Fragment。
2、在MainActivity的onCreate时加载Fragment1。

生命周期调用Log:
[MainActivity] onCreate start
[MainActivity] onCreate end
[MainActivity] onStart start
[Fragment1] onAttach
[Fragment1] onCreate
[Fragment1] onCreateView
[Fragment1] onViewCreated
[Fragment1] onActivityCreated
[Fragment1] onViewStateRestored
[Fragment1] onStart
[MainActivity] onStart end
[MainActivity] onResume start
[Fragment1] onResume
[MainActivity] onResume end

3、点击Fragment1中的按钮,通过Replace的方式显示Fragment2,同时将Fragment1压栈。

生命周期调用Log:
[Fragment2] onAttach
[Fragment2] onCreate
[Fragment1] onPause
[Fragment1] onStop
[Fragment1] onDestroyView
[Fragment2] onCreateView
[Fragment2] onViewCreated
[Fragment2] onActivityCreated
[Fragment2] onViewStateRestored
[Fragment2] onStart
[Fragment2] onResume

4、Fragment2点击返回,弹栈显示Fragment1。

生命周期调用Log:
[Fragment2] onPause
[Fragment2] onStop
[Fragment2] onDestroyView
[Fragment2] onDestroy
[Fragment2] onDetach
[Fragment1] onCreateView
[Fragment1] onViewCreated
[Fragment1] onActivityCreated
[Fragment1] onViewStateRestored
[Fragment1] onStart
[Fragment1] onResume

Replace及压栈的代码如下:

	getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.content_frame, fragment)	// 替换
            .addToBackStack(null)
            .commit();

弹栈的代码如下:

public void goBack() {
    if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
		getSupportFragmentManager().popBackStack();
	}
}

结论

由以上Log来看,被压入栈的Fragment不会调用onDestroy,因此弹栈显示的时候不会再调用onCreate,写代码的时候需要注意。

参考文章
https://www.cnblogs.com/LangZXG/p/6501839.html
https://blog.csdn.net/eyishion/article/details/54318740

你可能感兴趣的:(Android开发笔记)