Fragment懒加载

public class HomeFragment extends Fragment{
    private boolean isInitView = false;
    private boolean isVisible = false;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home, container, false);
        //如果绑定控件的话这里绑定注册
        //unbinder = ButterKnife.bind(this, view);
        isInitView = true;
        isCanLoadData();

        return view;
    }
    //重写setUserVisibleHint方法
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isVisible = true;
            isCanLoadData();
        } else {
            isVisible = false;
        }
    }

    private void isCanLoadData() {
        if (isInitView && isVisible) {
            lazyLoad();
            //防止重复加载数据
            isInitView = false;
            isVisible = false;
        }
    }
    private void lazyLoad(){
      //加载的数据及内容
      
    }

}

你可能感兴趣的:(Fragment懒加载)