Search code examples
androidfragmentscreen-orientationfragmenttransaction

Wrong replaced fragment view after screen orietation change


App has fragment activity with framelayout container matching parent. User interacts with fragments ui and they replaced each other, putting old in backstack, such as: A -> B -> C -> D -> E -> F

When user changes phone orientation, for example, on fragment D and wants to go to fragment E, the view of fragment A shows, and if user presses something in this fragment A (which normally goes to fragment B), the view of fragment F shows.

How to show fragment E and not A after screen orientation change?

App uses latest android support library and this happens in android 4.1 emulator and android 2.3 phone (not tested other android versions).

All fragments have this go next fragment method:

public final void showNextFragment(final Fragment frg, final String tag) {
    final FragmentTransaction tr = getFragmentManager().beginTransaction();
    tr.remove(this);
    tr.add(R.id.fragment_container, frg, tag);
    tr.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    tr.addToBackStack(tag);
    tr.commit();
}

Edit

When rotating screen on fragment D, all rotation goes normally and shows view of fragment D. Problem that after rotation if user goes to fragment E using method above, the view of fragment A shows instead of E. If user not rotates phone fragment E shows normally.


Solution

  • One solution is to keep the current tag or fragment as a static variable.

    Otherwise, do you want to go back to A on screen orientation? If not you should add this in your manifest:

    <activity android:configChanges="keyboardHidden|orientation" ...