Android Fragment懒加载
BaseLazyFragment
public abstract class BaseMvpLazyFragment<P extends BaseContract.IPresenter> extends BaseMvpFragment<P> {
protected boolean isActivityCreated;
protected boolean isVisibleToUser;
protected boolean isDataInitiated;
@Override
protected void initData() {
isActivityCreated = true;
prepareFetchData();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
this.isVisibleToUser = isVisibleToUser;
prepareFetchData();
}
public boolean prepareFetchData() {
return prepareFetchData(false);
}
public boolean prepareFetchData(boolean forceUpdate) {
if (isActivityCreated && isVisibleToUser && (!isDataInitiated || forceUpdate)) {
initLazyData();
isDataInitiated = true;
return true;
}
return false;
}
protected abstract void initLazyData();
public void setDataInitiated() {
this.isDataInitiated = true;
}
}
BaseMvpFragment
public abstract class BaseMvpFragment<P extends BaseContract.IPresenter> extends BaseFragment implements BaseContract.IView {
protected P mPresenter;
@Override
protected void initMvp() {
super.initMvp();
initPresenter();
if (mPresenter != null) {
mPresenter.attachView(this);
}
}
protected abstract void initPresenter();
@Override
public void onDestroy() {
super.onDestroy();
if (mPresenter != null) {
mPresenter.detachView();
mPresenter = null;
}
}
@Override
public void showError(String msg) {
}
@Override
public void complete() {
}
}
BaseContract
public interface BaseContract {
interface IView {
void showError(String msg);
void complete();
}
interface IPresenter<T> {
void attachView(T view);
void detachView();
}
}