My program has 6 fragments: Fragment1, Fragment2,....->Fragment6.
I use the add() and replace() statement to switch between the fragment and track their lifecycle.
Fragment1 add Fragment2 add Fragment3 add Fragment4 add Fragment5 replace Fragment6
The log-cat to shown their lifecycle (i have some printf-points in onCreate, onCreateView, onDestroyView, onDestroy for tracking)
Tag ______________ Text
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
Fragment5 _______ replace Fragment6
Fragment1 _______ onDestroyView
Fragment3 _______ onDestroyView
Fragment5 _______ onDestroyView
Fragment6_________onCreate
Fragment6_________onCreateView
My questions:
Why after the Fragment5 is replaced by Fragment6, the Fragment1 & 3 &5 are destroyed their view ?.
What is happending with Fragment2 & 4 ?
Why Fragment2 & 4 are not destroyed their view as Fragment1 & 3 &5 ?
Please help me to understand fully about fragment's lifecycle when call the add() and replace() method.
Update my addFragment and replaceFragment method:
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();
}
See Question&Answers more detail:
os