I have put together a simple program that uses fragment replacement with a single activity and two fragments. One fragment has a button, that when pressed, replaces the frag
The answer is simple. UI state is retained across screen rotations meaning if you do nothing the screen would still show the second fragment once you rotate. Since you add the first fragment in your Activity onCreate method it will be added to what is already shown hence the two fragments overlap.
You could do something like this:
FragmentManager mgr = getFragmentManager();
if (mgr.findFragmentByTag("start") == null &&
mgr.findFragmentByTag("replacementTest") == null) {
FragmentTransaction t = mgr.beginTransaction();
t.add(R.id.fragment_container, startingFragment, "start").commit();
}
@Emanuel is correct that the UI state is retained across screen rotations. However what's happening is simply that your Activity's onCreate is always called on rotation, which always adds your startingFragment
The solution is simple. Just add a condition in your onCreate as so to handle the case when it's called as part of the activity lifecycle:
if (savedInstanceState == null)
{
FragmentTransaction t = getFragmentManager().beginTransaction();
t.add(R.id.fragment_container, startingFragment, "start").commit();
}
You might want to consider doing
t.replace(R.id.fragment_container, startingFragment, "start").commit();
though instead of
t.add(R.id.fragment_container, startingFragment, "start").commit();