Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

mViewPager.setOffscreenPageLimit(0);
mViewPager.setAdapter(mPagerAdapter);

My FragmentStatePagerAdapter.getItem(int position) override function is called 3 times, which is what happens when I call mViewPager.setOffscreenPageLimit(1). I would expect it to only be called once, because I specified 0 offscreen pages.

I believe I'm calling everything correctly, because if I call mViewPager.setOffscreenPageLimit(2), FragmentStatePagerAdapter.getItem(int position) is called 5 times as I would expect.

Does ViewPager require a minimum of 1 offscreen pages, or am I doing something wrong here?

like image 932
Chris Lacy Avatar asked Apr 09 '12 12:04

Chris Lacy


3 Answers

The best way that I found was setUserVisibleHint
add this to your fragment

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // load data here
    }else{
       // fragment is no longer visible
    }
}
like image 157
Tyler Davis Avatar answered Oct 05 '22 21:10

Tyler Davis


Does ViewPager require a minimum of 1 offscreen pages

Yes. If I am reading the source code correctly, you should be getting a warning about this in LogCat, something like:

Requested offscreen page limit 0 too small; defaulting to 1
like image 40
CommonsWare Avatar answered Oct 05 '22 22:10

CommonsWare


You can try like this :

public abstract class LazyFragment extends Fragment {
    protected boolean isVisible;
    /**
     * 在这里实现Fragment数据的缓加载.
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }
    protected void onVisible(){
        lazyLoad();
    }
    protected abstract void lazyLoad();
    protected void onInvisible(){}
protected abstract void lazyLoad();
protected void onInvisible(){}
like image 23
Terry Avatar answered Oct 05 '22 21:10

Terry