In my open source Android app, an issue has been discovered where a specific fragment will come into view on top of another fragment or crash the app in a certain situation.
The issue on GitHub if you want to see more information and example screenshots:
I have pinned down the reason, but want to know which of the methods in the android.support.v4.app package to use to resolve the issue.
ViewMapFragment vmf = new ViewMapFragment();
FragmentTransaction ft = getSherlockActivity().getSupportFragmentManager().beginTransaction();
FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
According to the documentation of FragmentTransaction, when you invoke addToBackStack method it just remembers what actions you perform in that transaction. When popBackStack method is invoked it will reverse those actions and execute them.
So, what happens:
There is several options to handle such a situation:
To clear back stack you can use this code (related question):
If you put this line in the beginning of your selectItem method the bug will be fixed.
And your questions:
Example. For instance, we have added a fragment with tag "fragment-1":
getSupportFragmentManager() .beginTransaction() .replace(R.id.frame, new TestFragment(), "fragment-1") .commit();
Then, we put it into a back stack and replace it with another fragment:
getSupportFragmentManager() .beginTransaction() .addToBackStack(null) .replace(R.id.frame, new TestFragment(), "another-fragment") .commit();
At this point getSupportFragmentManager().findFragmentByTag("fragment-1") returns our first fragment (it gets it from a back stack entry). Now we can check whether this fragment is added to its activity by isAdded method - if it returns false, then we can make an assumption that the fragment is in a back stack.