Search code examples
androidandroid-fragmentsfragmentmanagerfragmenttransaction

FragmentTransaction add fragment after replace old fragment but onDestroyView called


I replaced FragmentA :

 FragmentManager fm = MainActivity.getGlobal().getSupportFragmentManager();
 FragmentTransaction ft = fm.beginTransaction();
 ft.addToBackStack(fragmentA.getClass().getSimpleName());
 ft.replace(relId, fragmentA,fragmentA.getClass().getSimpleName());
 ft.commitAllowingStateLoss();

and add FragmentB :

FragmentManager fm = MainActivity.getGlobal().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(relId, fragmentB);
ft.commitAllowingStateLoss();

After adding FragmentA:onDestroyView called, How fix it? I want FragmentB to add and Fragment Not DestroyView

thanks


Solution

  • A call to replace() is analogous to calling remove() on A and them calling add() on B hence it is not possible to save A when you replace it it's onDestroy(), onDestroyView() etc will be called.

    But instead of calling replace() you can call add() for B add B on top of A without removing A and add B to back stack to navigate to A on back press

    Have a good day , Ali