Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewPager.setOffscreenPageLimit(0) has no effect at all. How do I only load one page at a time in a ViewPager?

even when I set oViewPager.setOffscreenPageLimit(0) my view pager still loads 1 off screen page on each side of the visible page.

How do I make it only load the page when the user slides to it?

My adapter if it helps:

public class MainPagerAdapter extends FragmentPagerAdapter {
    protected static final String[] CONTENT = new String[] { "page 1", "page 2", "page 3", "page 4", };

    private int mCount = CONTENT.length;

    public MainPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        //return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
        return MainFragment.newInstance(position);
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
      return MainPagerAdapter.CONTENT[position % CONTENT.length];
    }

    public void setCount(int count) {
        if (count > 0 && count <= 10) {
            mCount = count;
            notifyDataSetChanged();
        }
    }


}
like image 274
code511788465541441 Avatar asked Jul 30 '13 13:07

code511788465541441


3 Answers

Another alternative is to use a OnPageChangeListener, and whenever a page change occurs call a refresh method in your fragments.

This will require you to set a higher OffScreenPageLimit, but the fragments will be updated every time one is brought into view.

pager.setOnPageChangeListener(new OnPageChangeListener() {

     @Override
     public void onPageSelected(int position){
         ((MyRefreshableFragment)pager.getAdapter().getItem(position)).refresh();
     }

     @Override
     public void onPageScrolled(int arg0, float arg1, int arg2) {}
     @Override
     public void onPageScrollStateChanged(int arg0) {}
  });
like image 127
edthethird Avatar answered Oct 01 '22 06:10

edthethird


How do I make it only load the page when the user slides to it?

Write your own ViewPager. As is noted by Jani's answer, ViewPager has a minimum offscreen page limit of 1 to each side.

This is required for the swiping animation to work smoothly. Otherwise, if we had to wait for you to set up the UI for the next page, the user's swipe would be frozen, or swipe to blank content, for however long it takes you to get that UI established.

like image 44
CommonsWare Avatar answered Oct 01 '22 04:10

CommonsWare


You cant do this. You will get an error like: "Requested offscreen page limit 0 too small; defaulting to 1". But here you can find more about it: ViewPager.setOffscreenPageLimit(0) doesn't work as expected

like image 30
Jani Bela Avatar answered Oct 01 '22 06:10

Jani Bela