我的程序有6个片段:Fragment1,Fragment2,….-> Fragment6.
我使用add()和replace()语句在片段之间切换并跟踪其生命周期.
Fragment1添加Fragment2添加Fragment3添加Fragment4添加Fragment5替换Fragment6
log-cat显示他们的生命周期(我有一些printf点在onCreate,onCreateView,onDestroyView,onDestroy进行跟踪)
标签______________文字
Fragment1_________onCreate
Fragment1_________onCreateView
Fragment1_________add Fragment2
Fragment2_________onCreate
Fragment2_________onCreateView
Fragment2_________add Fragment3
Fragment3_________onCreate
Fragment3_________onCreateView
Fragment3_________add Fragment4
Fragment4_________onCreate
Fragment4_________onCreateView
Fragment4_________add Fragment5
Fragment5_________onCreate
Fragment5_________onCreateView
片段5 _______替换片段6
片段1 _______ onDestroyView
片段3 _______ onDestroyView
片段5 _______ onDestroyView
Fragment6_________onCreate
Fragment6_________onCreateView
我的问题:
为什么在Fragment5被Fragment6替代之后,Fragment1& 3和5被毁了他们的看法?
什么是Fragment2& 4?
为什么Fragment2& 4没有破坏他们的看法作为Fragment1& 3& 5?
调用add()和replace()方法时,请帮助我充分了解fragment的生命周期.
更新我的addFragment和replaceFragment方法:
public void addFragment(Fragment fromFragment, Fragment toFragment) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,toFragment, toFragment.getClass().getName());
transaction.hide(fromFragment);
transaction.addToBackStack(toFragment.getClass().getName());
transaction.commit();
}
public void replaceFragment(Fragment fromFragment, Fragment toFragment) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,toFragment, toFragment.getClass().getName());
transaction.hide(fromFragment);
transaction.addToBackStack(toFragment.getClass().getName());
transaction.commit();
}