I have 3 fragment A, B,C.I wrote piece of code for replacing them and maintaining backstack:
public void addFragment(Fragment fragmentToAdd, String fragmentTag)
I solved this problem by inheriting (1) all fragments from my custom BaseFragment (2). In this BaseFragment I created a variable: public static boolean removing; (3) and set it to true (4) before calling popBackStackImmediate() and reset it to false after that. (5) In the BaseFragment-childs I check the variable. (6)
Example-Code
Activity-class
BaseFragment.removing = true; //(4)
//pop all fragments
while(getSupportFragmentManager().getBackStackEntryCount() > 0){
fragmentManager.popBackStackImmediate();
}
BaseFragment.removing = false; //(5)
BaseFragment (2)
public class BaseFragment extends Fragment{
public static boolean removing = false; //(3)
}
Fragment-Child
public class fragment extends BaseFragment{ //(1)
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
if(!removing){ // (6)
//your code
}
}
}