问题背景:有的场景,Viewpager在每次切换Pager的时候去请求网络数据,刷新页面,同时在不显示的时候,又不会提前去请求数据。这就涉及到了Viewpager的预加载问题。
首先分析ViewPager预加载的原因
查看ViewPager的源码,发现第三行就定义了一个DEFAULT_OFFSCREEN_PAGES的变量,同时又将这个变量赋值给了mOffscreenPageLimit的变量。从变量的命名上,可以看出就是预加载的范围。接着通过查找可以发现,ViewPager设置预加载范围的方法。
源码展示如下:
private static final int DEFAULT_OFFSCREEN_PAGES = 1;
private int mOffscreenPageLimit = DEFAULT_OFFSCREEN_PAGES;
从代码的注释来看,可以看出,这个方法就是用来规定,预加载的范围的,但是,代码中也写明了。最小范围是1,也就是左右范围1页。
/**
* Set the number of pages that should be retained to either side of the
* current page in the view hierarchy in an idle state. Pages beyond this
* limit will be recreated from the adapter when needed.
*
* <p>Thi