(Base系列三)BaseFragment BaseMVPFragment封装

心情不好,持续了好久了,直接看BaseFragment代码吧

private boolean isViewCreated;
protected boolean isInitData;

private Unbinder mUnBinder;
protected Context mContext;
private CompositeDisposable mCompositeDisposable;
private List observerList;
private View view;

声明一些参数,俩个boolean变量用来控制fragment懒加载,Contenx其实就是BaseActivity对象,省得使用getActivity()方法,该方法有时候会返回null的,

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.mContext = context;
}

赋值mContext

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (null == view) {
        view = inflater.inflate(getLayout(), container, false);
        mUnBinder = ButterKnife.bind(this, view);
        isViewCreated = true;
    } else {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (null != parent) {
            parent.removeView(view);
        }
    }
    return view;
}

protected abstract int getLayout();// 抽象方法,子类返回布局id

onCreateView方法,进行null判断是可以避免一个多次添加view曝出的异常,具体异常名有点忘了……失败啊,同时赋值isViewCreated = true

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if(getUserVisibleHint()) {
        initData();
    }
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser && isViewCreated && !isInitData) {
        initData();
    }
}

protected void initData() {
    isInitData = true;
}

这就是懒加载及避免切换fragment导致的重复加载的核心代码了,在fragment显示隐藏及activity创建的时候进行initData()初始化,这块其实耦合感觉比较严重,必须重写initData()方法,不然isinitData无法赋值,有什么好的想法希望能指教一下我

public void showLoadingDialog(String msg, boolean cancelable) {
    ((BaseActivity) mContext).showLoadingDialog(msg, cancelable);
}

以这个为例说一下就ok了,和BaseActivity里的其实一样,强转mContext就可以,所有方法和BaseActivity里同步,同理addDisposableaddObserver及其销毁原理和BaseActivity一样,不赘述了,这就其实已经是完整的BaseFragment了,BaseMVPFragment代码更是简单

public abstract class BaseMVPFragment

extends BaseFragment implements BaseView{ protected P mPresenter; }

一行代码…. 以上,最近心情真的不好,写的不行,以后有时间重新编辑吧。

你可能感兴趣的:(android)