简体   繁体   English

使用ViewPager在屏幕旋转后缓存片段吗?

[英]Using ViewPager caches Fragments after screen rotation?

I initially create my fragments inside the Activity onCreate(). 我最初在Activity onCreate()中创建片段。 Than I go about creating the ViewPager and setting up the adapter. 比起创建ViewPager和设置适配器。 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...?? 我的问题是,一旦屏幕旋转,我会注意到重新创建了片段,但ViewPager仍然包含创建的原始片段...?

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);
}

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.). 除非您在片段上调用setRetainInstance() ,否则它将在重新创建父活动(在屏幕旋转等)时被序列化为Bundle并重新创建。 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. 您应该根据需要通过FragmentManager.findFragmentById/Tag()获取对片段的引用,并且绝对不要将其存储在静态变量中。

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. 您可能需要显示更多代码,但是只要您在onCreate()创建片段,这些引用就应该在活动的生命周期内有效。 Check the compatibility library sample code for more on using fragments with ViewPager . 检查兼容性库示例代码,以获取有关将片段与ViewPager一起使用的更多ViewPager

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM