Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ViewPager caches Fragments after screen rotation?

I initially create my fragments inside the Activity onCreate(). Than I go about creating the ViewPager and setting up the adapter. I keep a global reference to the fragments so I can update them as needed. Also, these fragments are accessed by the adapter.

My issue is that I notice once the screen is rotated the Fragments are recreated but the ViewPager still contains the original fragments created...??

How am I supposed to handle the life-cycle of my fragment? I need to be able to call directly to the fragment from the activity. Is a singleton for a fragment a good idea? Or just a memory leaker?

protected void onCreate (Bundle savedInstanceState)
{
...
...
        // set up cards
        mFrag1 = new Frag1();
        mFrag1.setOnActionEventListener(mOnActionEvents);

        mFrag2 = new Frag2();
        mFrag3 = new Frag3();

        mFragPager = (ViewPager) findViewById(R.id.vpPager);
        mFragAdapter = new FragAdapter(getSupportFragmentManager());
        mFragPager.setAdapter(mCardAdapter);
        mFragPager.setOnPageChangeListener(mOnCardChange);
}
like image 723
Jona Avatar asked Nov 20 '11 21:11

Jona


1 Answers

Global instances and static fragments are definitely a bad idea. Unless you call setRetainInstance() on a fragment, it will be serialized to a Bundle and recreated when an the parent activity is re-created (on screen rotate, etc.). That will, of course, produce new fragment instances, and your old references will be invalid. You should get references to fragments via FragmentManager.findFragmentById/Tag() as needed and definitely not store those in static variables.

You may need to show more of our code, but as long as you create the fragments in onCreate() the references should be valid for the lifetime of the activity. Check the compatibility library sample code for more on using fragments with ViewPager.

like image 77
Nikolay Elenkov Avatar answered Oct 13 '22 22:10

Nikolay Elenkov