Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle savedInstanceState when using ViewPager?

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?

like image 321
emmby Avatar asked May 23 '12 23:05

emmby


People also ask

What is the use of savedInstanceState in Android?

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.

How to include Fragment in activity?

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.

How to maintain Fragment state in Android?

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.

How do you save a fragment in savedInstanceState?

Here is an example: @Override protected void onCreate(Bundle savedInstanceState) { super. onCreate(savedInstanceState); if (savedInstanceState == null) { myFragment = MyFragment. newInstance(); getSupportFragmentManager() .


1 Answers

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.

like image 175
emmby Avatar answered Oct 04 '22 02:10

emmby