It’s takes me about few hours to debug why the detail fragment lost after i change the orientation. Here is the case,
home activity (with navigation drawer) will load fragment A. When people click item in fragment A, it will going to fragment B.
1 | Home Activity -> Fragment A -> Fragment B |
When, we change rotation, Android will remove all fragment in Backstack. So here is the cure :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); Configuration configuration = getActivity().getResources().getConfiguration(); // create a Fragment Fragment detailFragment = new DetailFragment(); detailFragment.setArguments(args); final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.popenter, R.anim.popexit); // Check if the device is landscape or portrait int ori = configuration.orientation; fragmentTransaction.replace(R.id.content_frame, detailFragment); if (ori == configuration.ORIENTATION_PORTRAIT) { fragmentTransaction.addToBackStack(null); } else { fragmentTransaction.addToBackStack("tag"); } fragmentTransaction.commit(); |
See on last line, which i put backstack null for portrait orientation. This solve the issue 🙂