您的位置:首页 > 移动开发 > Android开发

Android中MVP模式的抽象MVP类,减少代码量,增加中断机制(三)

2017-12-24 00:28 507 查看
(本篇文章基于前两篇文章基础之上)

好了,内存泄漏解决了,现在解决下冗余的代码量。

回顾下上文

public void attach(RequestView view) {
this.mRequestView = view;
}

public void detach() {
mRequestView = null;
}

public void interruptHttp() {
mRequestModel.interruptRequest();
}

这3个操作是MainActivity中的,很冗余,而且可以说每个MVP都会有,所以这3个可以抽象。

我们需要创建抽象V接口类,抽象(为了以后V有公共操作,放这里)

public interface BaseRequestView {
}

增加BaseRequestActivity

public abstract class BaseRequestActivity<V extends BaseRequestView, P extends BaseRequestPresenter<V>>
extends BaseActivity implements BaseRequestView{
private P presenter;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (presenter == null) {
presenter = createPresenter();
}
if (presenter == null) {
throw new NullPointerException("presenter返回值为空!");
}
presenter.attach((V)this);
}

@Override
protected void onDestroy() {
super.onDestroy();
if (presenter != null) {
presenter.detach();
}
}

protected abstract P createPresenter();

public P getPresenter() {
return presenter;
}
}

不仅把绑定、解绑的操作抽象了,还抽象了部分创建P的代码。

最后是P的抽象类

public abstract class BaseRequestPresenter<V extends BaseRequestView> {
private V mView;

public void attach(V view) {
mView = view;
}

public void detach() {
mView = null;
}

public V getView() {
return mView;
}
}


最后个人喜欢中断机制 就保留了中断机制



不仅activity退出会中断网络请求,点击dialog外面的部分也会中断,非常的人性化。(不仅是中断网络请求,其他形式的中断也有,所以我保留了中断机制)

PS:ProgressDialog点击外面部分中断的代码

dialog = ProgressDialog.show(this, "提示", "正在登陆中", false, true, new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
getPresenter().interrupt();
}
});

最后一个true是点击屏幕外面可取消,这个监听是监听dialog消失的监听,不管按返回键还是点击外面都能监听到

最后的最后onCreate也给抽象掉了,所以看一下BaseActivity的代码

public abstract class BaseActivity extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (initBundle(getIntent().getExtras())) {
setContentView(getContentView());

ButterKnife.bind(this);
initData();
initWidget();
} else {
finish();
}
}

protected void initData() {

}

protected void initWidget() {

}

protected abstract int getContentView();

protected boolean initBundle(Bundle bundle) {
return true;
}
}


子类

@Override
protected int getContentView() {
return R.layout.activity_main;
}


github地址:https://github.com/xubinhong/MVP2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: