So I have four fragments (A,B,C and D). I use buttons to navigate between them and if I for example go from A to B and from B to A it loads A again and I don't want it to happen.
This is a code I'm calling to load fragment into container :
public void showNewFragment(Class<? extends Fragment> fragmentClass, Integer whereToPlaceId, Bundle bundle)
{
String tag = fragmentClass.getSimpleName();
FragmentManager fm = getSupportFragmentManager();
boolean inStack = fm.popBackStackImmediate(tag,0);
FragmentTransaction fragTM = fm.beginTransaction();
if(!inStack) {
try {
fragTM.add(whereToPlaceId, fragmentClass.newInstance(), tag);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
fragTM.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragTM.addToBackStack(tag);
fragTM.commit();
}
Also I tried with onSaveInstanceState but it's only called when config change is made.
Also in activity which holds this fragments I disabled back button navigation.
EDIT :
I did this in my fragment
public static View rootView = null;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(rootView != null)
return rootView;
//if not init rootView
return rootView;
}
Is this good approach ?