ViewPager 有个坑爹的方法,该方法设置预加载的个数,但不能设置成0,因为ViewPager中有个默认的判断。
DEFAULT_OFFSCREEN_PAGES = 1,即最少要是1个
setOffscreenPageLimit
public void setOffscreenPageLimit(int limit) { if (limit < DEFAULT_OFFSCREEN_PAGES) { Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " + DEFAULT_OFFSCREEN_PAGES); limit = DEFAULT_OFFSCREEN_PAGES; } if (limit != mOffscreenPageLimit) { mOffscreenPageLimit = limit; populate(); }}
2. 所以只能通过setUserVisibleHint方法,设置延迟加载来实现
public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if(getUserVisibleHint()) { isVisible = true; onVisible(); } else { isVisible = false; }}protected void onVisible(){ lazyLoad();}protected abstract void lazyLoad();
3. ViewPager会在设置Adapter之后立即调用第一个、第二个fragment的setUserVisibleHint(boolean)方法设置为false,然后会对第一个fragment再次调用setUserVisibleHint(boolean)方法设置为true,然后才是onAttach()、onCreate(),所以需要增加变量判断
我获取数据是在onActivityCreated中调用
public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); isActivityCreated = true;}
4. 调用时判断两个变量
protected void lazyLoad() { if (!isActivityCreated || !isVisible) { return; } onRefresh();}