Search code examples
androidandroid-viewpagerfragmentstatepageradapterandroid-pageradapter

Creates more items on instantiateItem and not only one as default


I have an adapter (FragmentStatePagerAdapter) with arrows, that each click creates the next page:

    leftArrow.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
        }
    });
    rightArrow.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);

        }
    });

@Override
public Object instantiateItem(ViewGroup collection, int position) {
    int i=0;
    for (i=position; i<position+2;i++){
    MyPage currentPage = pages.get(i);
    if(page == null){
        currentPage = new MyPage(i);
        pages.put(i, page);     
        super.instantiateItem(collection, i);
    }
    }

    return super.instantiateItem(collection, position);
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    MyPage pageToRemove = pages.get(position);
    if(pageToRemove != null){
        pageToRemove.dispose();
        pages.remove(position);
    }
    super.destroyItem(container, position, object);
}
}

I want to create on each iteration not 1 page but 3, because I have delays while paging. I tried to create the pages and insert them into array but the problem is that I have only ONE return that return return super.instantiateItem(collection, position);

Any ideas how can I call it few more times?


Solution

  • Any ideas how can I call it few more times?

    You're not the one doing the calling -- ViewPager is. You can call setOffscreenPageLimit() to increase the number of pages that ViewPager will cache. By default, the value is 1, meaning that ViewPager will cache 3 pages (the current one, plus one to either side). Bumping that to 2 will have ViewPager cache 5 pages, and so on.

    Bear in mind:

    • This slows down setting up the ViewPager, and so it is not really a solution for slow pages

    • This consumes more heap space