ViewPager.setOffscreenPageLimit(0) has no effect a

2020-02-07 00:39发布

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


}

8条回答
家丑人穷心不美
2楼-- · 2020-02-07 01:35

I use a Loader and init the loaders of each fragment in the onPageSelected.

查看更多
▲ chillily
3楼-- · 2020-02-07 01:43

I know this is very late answer but for God's sake you do not have to write your own viewpager as someone suggested.

Lets take things from start:

How viewpager works:

By default it keeps one item in memory either side so it does not have to create it everytime.

1st Solution:

mViewPager.setOffscreenPageLimit(0);

which results to:

Requested offscreen page limit 0 too small; defaulting to 1

2nd Solution:

You want to update the Fragment when it is actually visible to the user so use the method:

@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
           //Do something like 
           //adapter.notifyDataSetChanged();
        }
    }

Hope it helps someone in the future!!!

查看更多
登录 后发表回答