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)
Than behavior is normal, coming from the backstack transaction, as the docs say. The backstack never saves Fragments, it just saves the transaction
http://developer.android.com/intl/es/guide/components/fragments.html
What I do, I am not sure if, is it the best way but when I want to clear all the transactions I do this
1) INSIDE YOUR ACTIVITY check if is there any transactions in the back stack, and add a flag inside your fragment, in your case is A
int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
if(backStackCount > 0) {
Transactions.MUST_DETACH_FROM_BACKSTACK = true;
getSupportFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
2) Inside your fragment A, get the flag and Remove the fragment onCreateView
and return null like this
public class Transactions extends android.support.v4.app.Fragment{
public static boolean MUST_DETACH_FROM_BACKSTACK = false;
public Transactions() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("FRAGMENT", "onCreateView "+MUST_DETACH_FROM_BACKSTACK);
// Inflate the layout for this fragment
if (MUST_DETACH_FROM_BACKSTACK) {
MUST_DETACH_FROM_BACKSTACK = false;
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
return null;
}
return inflater.inflate(R.layout.fragment_transactions, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i("FRAGMENT", "onViewCreated");
if(view != null){
Log.i("FRAGMENT", "ThreadStarted");
startThread(view);
}
}
BUT BE CAREFULL I Get onResume() Called after the
OnCreateView()
even with getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
So if you have any conde onResume method you should handle it properly