So, there are some similar questions, but I have not found a single one solving this issue. The official android documentation seems intuitive but when I implement an app with a more complicated workflow, the fragments backstack gets messy and weird stuff starts happening. I developed a skeleton for simple apps, with the idea of a single activity which can be accessed by its fragments to start other fragments. This is how I did it:
1- I let my main activity implement an interface called "FragmentDelegate"
public interface FragmentDelegate {
public void startFragment(CCFragment fragment, boolean addToBackStack);
}
2- The implementation of the startFrargment method:
@Override
public void startFragment(CCFragment fragment, boolean addToBackStack) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragment.setFragmentDelegate(this);
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_right,
R.anim.slide_out_left, R.anim.slide_in_left,
R.anim.slide_out_right);
fragmentTransaction.replace(CONTENT_VIEW_ID, fragment,
"callerFragmentClassName");
if (addToBackStack)
fragmentTransaction.addToBackStack("callerFragmentClassName");
fragmentTransaction.commitAllowingStateLoss();
}
The cool thing about this is, I can call from any fragment:
mFragmentDelegate.startFragment(aNewFragment, addToBackStack);
OK now think of the following case scenario:
I start my activity with an initial fragment, lets say fragment A. From fragment A, I call the Camera Activity for a result. When the result arrives, I start Fragment B (adding A to the backstack). From B I start Fragment C without adding B to the backstack. So we have this in the backstack:
[A] [C]
If I press the back button, I get back to A. If I repeat the process, the backstack gets messed up and when I press back, it takes me to the C fragment again and again...
I know this is difficult to understand (and more difficult for me to explain, because English is not my mother tongue) but if someone could explain to me how do the android fragments backstack really work, or provide some kind of skeleton for an app, would be great.