Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This happens because on orientation change your fragments inside your viewpager are recreated so you create another fragment of the same type. But your first fragment is not destroyed and it just remains in the stack. So in the end you have one fragment for orientation Landscape and one for Portrait.</p> <p>Passing null to the onCreate solves your problem because the previous fragment is not recreated, but it is just wrong as you will probably have other problems if you use this approach;</p> <p>What you have to do to fix your problem is to check if the fragment already exists in the fragment manager then if it exists return that fragment or if it isn't create a new one and commit the transaction!</p> <p>An example code for this is below (taken from one of my test files).</p> <pre><code> MFragment fragment1; if (fragmentManager().findFragmentByTag("android:switcher:" + R.id.viewpager + ":" + 0) == null) { M.LogLifecycle("Fragment1", "does not exists so instantiate"); fragment1 = MFragment.instance("Example"); } else { M.LogLifecycle("Fragment1", "exists so retrieve instance"); fragment1 = (MFragment) fragmentManager().findFragmentByTag("android:switcher:" + R.id.viewpager + ":" + 0); } </code></pre> <p>Check <code>"android:switcher:" + R.id.viewpager + ":" + position</code> which is by default the way FragmentPagerAdapter stores fragment in the FragmentManager, where R.id.viewpager is the id of your viewpager in the layout and position is the position of your fragment inside the viewpager.</p> <p>I can give you only an example of how to implement it inside viewpager because you haven't added much code of your project.</p> <p><em>The general idea with fragments is to check if they exists in the fragmentManager before committing a transaction otherwise you may create duplicates.</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload