博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ViewPager+Fragment+Tab延迟加载页面(懒加载)
阅读量:6937 次
发布时间:2019-06-27

本文共 1036 字,大约阅读时间需要 3 分钟。

hot3.png

ViewPager里面滑动页面时,我们希望要滑到的页面不要立即显示,要等到我们来到这一页后再显示loading,然后刷出数据(也叫懒加载)。上代码:

public abstract class LazyLoadFragment extends Fragment {    private boolean mHasLoadedOnce;    private boolean mViewCreated;    protected abstract void doLoad();    @Override    public void onViewCreated(View view, Bundle savedInstanceState) {        mViewCreated = true;        loadIfNeeded();    }    @Override    public void setUserVisibleHint(boolean isVisibleToUser) {        super.setUserVisibleHint(isVisibleToUser);        loadIfNeeded();    }    private void loadIfNeeded() {        if (getUserVisibleHint() && mViewCreated && !mHasLoadedOnce) {            doLoad();            mHasLoadedOnce = true;        }    }}

setUserVisibleHint()这个核心方法会在ViewPager的populate()里面被调用, 当其传人的参数isVisibleToUser为true时,表示对用户可见,此时再去联网取数据,就有延迟加载的效果。但这个方法会在onCreateView()之前被调用,在setUserVisibleHint()里面也要检测是否view已经创建、是否已加载过数据。

还有一点,我们要调用"ViewPager.setOffscreenPageLimit(4)"使不可见的页面也一直存活。这个做法比较耗内存,目前还没有找到更好的方法。

最后,贴出完整示例代码的下载地址:

转载于:https://my.oschina.net/TedzycRs/blog/472257

你可能感兴趣的文章
13. Spring Boot 拦截器
查看>>
bootstrap Grid布局(网格布局)
查看>>
java实现HeapSort
查看>>
Spring 事务
查看>>
MySQL 中国省市区SQL表数据
查看>>
HTML5取代不了Flash
查看>>
BNU52325-Increasing or Decreasing-数位DP-DFS
查看>>
JDK源码阅读--StringBuffer
查看>>
(45) Manifest文件
查看>>
微信小程序中的bindTap事件(微信小程序开发QQ群:604788754)
查看>>
九度 1149 子串计算
查看>>
消息中间件基础
查看>>
IIS特殊字符设置
查看>>
javascript 函数对象
查看>>
js中作用域链的问题
查看>>
[Silverlight] How to make a simple PivotTable extended from Silverlight DataGrid
查看>>
javaScript 基本包装类型
查看>>
Can not find the tag library descriptor for "http://java.sun.com/jstl/core_rt"
查看>>
Java多线程之Thread、Runnable、Callable及线程池
查看>>
canvas刮奖
查看>>