ViewPager2+Fragment实现懒加载

1、pager.setOffscreenPageLimit(fragmentList.size());避免fragment销毁,重复创建
2、定义抽象类

  • 将Fragment加载数据的逻辑放到onResume()方法中,这样就保证了Fragment可见时才会加载数据。
  • 声明一个变量标记是否是首次执行onResume()方法,因为每次Fragment由不可见变为可见都会执行onResume()方法,需要防止数据的重复加载。
public abstract class LazyViewPager2Fragment extends Fragment implements View.OnClickListener{
    public static final String TAG = "LazyFragment";
    View rootView;
    private boolean isFirstLoad = true; // 是否第一次加载
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.i(TAG,"onCreateView");
        if(rootView == null){
            rootView = inflater.inflate(getLayoutId(),container,false);
        }
        initView(rootView);
        return rootView;
    }
    /**
     * 布局id
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 初始化控件
     * @param rootView
     */
    protected abstract void initView(View rootView);

    //数据加载
    public void onDataLoad(){
        Log.i(TAG,"onDataLoad");
    }
    //停止加载数据
    public void onDataLoadStop(){
        Log.i(TAG,"onDataLoadStop");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG,"onResume");
        if(isFirstLoad){
            onDataLoad();
            isFirstLoad = false;
        }
    }

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值