通俗易懂实现Fragment懒加载

2019-12-09  本文已影响0人  BusyBunny

Fragment懒加载的实现思路:

private boolean isVisibleToUser;//判断View是否可见

@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        this.isVisibleToUser=isVisibleToUser;
        lazyLoad();
    }
private boolean isViewPrepared;//View是否初始化完成;
 
 //Fragment的View的已加载完毕;
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    isViewPrepared=true;
}
private boolean isInitDataOver=false;//判断数据是否已经加载完成


 private void lazyLoad() {
        if (!isInitDataOver && isVisibleToUser &&isViewPrepared ){
            forceLoad=false;
            isInitDataOver=true;
            
            initData()//抽象方法
        }
}
 @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //对于第一个Fragment的时候,主动加载;
        lazyLoad();
    }

完整源码:

public class BaseFragment extends Fragment
    private boolean isInitDataOver;//判断数据是否加载完成
    private boolean isViewPrepared;//View是否初始化完成;
    private boolean isVisibleToUser;//判断View是否可见
    
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        this.isVisibleToUser=isVisibleToUser;
        lazyLoad();
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView==null){
            //填充内容页面
        }
        return mRootView;
    }
    
    //Fragment的View的已加载完毕;
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewPrepared=true;
    }
    
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //对于第一个Fragment的时候,主动加载;
        lazyLoad();
    }
    
    private void lazyLoad() {
        if (!isInitDataOver && isVisibleToUser &&isViewPrepared ){
            forceLoad=false;
           isInitDataOver=true;
            //在此实现加载数据
        }
}


上一篇下一篇

猜你喜欢

热点阅读