How to handle savedInstanceState when using ViewPager?

android, android-fragments

Solution

Never mind. It appears that I was using `FragmentPagerAdapter` incorrectly.

The correct way to use `FragmentPagerAdapter` is to instantiate your new fragment in `getItem()`. I was instantiating all my fragments in the adapter's constructor instead, storing them in an array, and then looking them up in the array and returning the appropriate fragment in `getItem()`.

If you instantiate your fragment from `getItem()`, then `FragmentPagerAdapter.instantiateItem()` will automatically use the recycle fragment instead of instantiating a new one.

Problem

I'm using `android.support.v4.view.ViewPager` in an application. When the user rotates the screen, the activity is destroyed and recreated. The fragments that are currently active in the `ViewPager` (usually the one on screen, the one to the left of it, and the one to the right of it) are all stored to the `savedInstanceState`. A new activity is created, `FragmentActivity.onCreate(savedInstanceState)` is called with the fragment state, and those three fragments are re-created using the bundle. However, my `onCreate` also sets up the `ViewPager` and `ViewPager` adapter, which create their own fragments afresh, thus resulting in TWO of each of those three fragments. How can I associate the automatically re-created fragments with my `ViewPager`'s adapter rather than re-creating them from scratch?

Original source