Prevent ViewPager from destroying off-screen views

前端 未结 3 2073
予麋鹿
予麋鹿 2020-12-02 04:59

I have a ViewPager hooked up to a FragmentPagerAdapter that\'s displaying three fragments. The ViewPager appears to destroy a hosted fragment\'s view when it is more than on

相关标签:
3条回答
  • 2020-12-02 05:23

    "Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed."

    http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit(int)

    0 讨论(0)
  • 2020-12-02 05:36

    By default, ViewPager recreates the fragments when you swipe the page. To prevent this, you can try one of two things:

    1. In the onCreate() of your fragments, call setRetainInstance(true).

    2. If the number of fragments is fixed & relatively small, then in your onCreate() add the following code:

    ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setOffscreenPageLimit(3);
    

    If I remember correctly, the second option is more promising. But I urge you to try both and see which of them work.

    0 讨论(0)
  • 2020-12-02 05:39

    In revision 4 of the Support Package, a method was added to ViewPager which allows you to specify the number of offscreen pages to use, rather than the default which is 1.

    In your case, you want to specify 2, so that when you are on the third page, the first one is not destroyed, and vice-versa.

    mViewPager = (ViewPager)findViewById(R.id.pager);
    mViewPager.setOffscreenPageLimit(2);
    
    0 讨论(0)
提交回复
热议问题