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?
The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity. Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle.
Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.
Various Android system operations can affect the state of your fragment. To ensure the user's state is saved, the Android framework automatically saves and restores the fragments and the back stack. Therefore, you need to ensure that any data in your fragment is saved and restored as well.
Here is an example: @Override protected void onCreate(Bundle savedInstanceState) { super. onCreate(savedInstanceState); if (savedInstanceState == null) { myFragment = MyFragment. newInstance(); getSupportFragmentManager() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With