懒加载的Fragment

·  阅读 86

实现一个懒加载的Fragment

仅需要子类在回调中做加载操作即可

package com.zhiup.base.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;


/**
 * Created by zhou on 2017/11/7 17:30 .
 */

public abstract class BaseLazyFragment extends Fragment {
    /**
     * 控件是否初始化完成
     */
    private boolean isViewCreated;
    /**
     * 数据是否已加载完毕
     */
    private boolean isLoadDataCompleted;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isViewCreated && !isLoadDataCompleted) {
            isLoadDataCompleted = true;
            inVisiableLoad();
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getUserVisibleHint()) {//当前可见则加载,否则由上面的setUserVisibleHint加载数据
            isLoadDataCompleted = true;
            inVisiableLoad();
        }
    }

    //在此方法的实现方法里面做getdata的操作即可。此方法仅在fragment第一次可见时执行
    public abstract void inVisiableLoad();

}

收藏成功!
已添加到「」, 点击更改