ViewPager.setOffscreenPageLimit(0) doesn't work as expected

前端 未结 11 984
抹茶落季
抹茶落季 2020-11-22 13:02

The fragments I use in my ViewPager instance are quite resource intensive, so I\'d only like to load one at a time. When I try the following:

mV         


        
11条回答
  •  醉话见心
    2020-11-22 13:57

    I kind of have the same problem. I found some useful code on this site and transform it.

    The min int for mViewPager.setOffscreenPageLimit(...); is 1, so even if you change it to 0 you will still have 2 pages loaded.

    First thing to do is to create a static int we will call maxPageCount and override FragmentStatePagerAdapter method getCount() to return maxPageCount:

        @Override
        public int getCount() {
            return maxPageCount;
        }
    

    Create then a static method accessible from any where in the program that will allow you to change this maxCount:

    public static void addPage(){
        maxPageCount++; //or maxPageCount = fragmentPosition+2
        mFragmentStatePagerAdapter.notifyDataSetChanged(); //notifyDataSetChanged is important here.
    }
    

    Now initialize maxPageCount to 1. When ever you want you can add another page. In my case when I needed the user to treat the current page first before generated the other. He do it and then, without problem can swipe to the next page.

    Hope it help someone.

提交回复
热议问题