MVP模式的基本使用

来源:互联网 发布:Linux 子系统 编辑:程序博客网 时间:2024/06/10 04:33

   废话不多说了,现在大部分程序员已经在用mvp了,今天简单的把代码贴出来,相互学习下!

首先就是基类,mvp无非就是 M-model层,V-view层,P-presenter 首先写出MVP层的基类,所以


首先是View 和 Model 接口

public interface IView {}
public interface IModel {}
接下来是写个presenter 用来回调控制m-v

public interface IPresenter <T extends IView> {    void attachView(T view, Context context);    void start(String url, Map<String, String> param);    void detachView();}
然后BasePresenter 实现这个接口,复写方法

public abstract class BasePresenter<T extends IView, M extends IModel> implements IPresenter<T> {    protected static final String TAG = "BasePresenter";    protected T mView;    protected M mModel;    protected Context context;    private Dialog mLoadingDialog;    @Override    public void attachView(T view, Context context) {        mView = view;        this.context = context;    }    @Override    public void detachView() {        context = null;        mView = null;        mModel = null;    }    public boolean isViewAttached() {        return mView != null && context != null;    }    public T getView() {        return mView;    }    public M getModel() {        return mModel;    }    public void showLoading(String content) {        View view = LayoutInflater.from(context).inflate(R.layout.dialog_loading, null);        TextView loadingText = (TextView) view.findViewById(R.id.text);        loadingText.setText(content);        mLoadingDialog = new Dialog(context, R.style.Dialog);        mLoadingDialog.setCancelable(false);        mLoadingDialog.setContentView(view,                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,                        LinearLayout.LayoutParams.MATCH_PARENT));        mLoadingDialog.show();    }    public void dismissLoading() {        if (mLoadingDialog != null) {            mLoadingDialog.dismiss();            mLoadingDialog = null;        }    }}
最后是activity的基类
public abstract class IViewActivity<P extends IPresenter> extends BaseActivity implements IView{    protected P mPresenter;    protected Map<String,String> param = new HashMap<>();    @Override    protected void onCreate(Bundle savedInstanceState) {        mPresenter = onLoadPresenter();        if (getPresenter() != null){            getPresenter().attachView(this,this);        }        super.onCreate(savedInstanceState);    }    public P getPresenter() {        return mPresenter;    }    @Override    protected void onDestroy() {        if (getPresenter() != null) {            getPresenter().detachView();        }        super.onDestroy();    }    protected abstract P onLoadPresenter();}

到这里基类就基本完成

至于如何运用,下篇博文发出。