ViewPager.setOffscreenPageLimit(0) 完全没有效果.如何在 ViewPager 中一次只加载一个页面?

2022-01-19 00:00:00 android android-viewpager java

即使我设置了 oViewPager.setOffscreenPageLimit(0),我的视图寻呼机仍会在可见页面的每一侧加载 1 个屏幕外页面.

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

如何让它只在用户滑动到页面时才加载?

如果有帮助,我的适配器:

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


}

推荐答案

另一种选择是使用 OnPageChangeListener,每当页面发生变化时,在您的 Fragment 中调用 refresh 方法.

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

这将要求您设置更高的 OffScreenPageLimit,但每次看到片段时都会更新片段.

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

相关文章