MVP模式的基本使用

   废话不多说了,现在大部分程序员已经在用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();

}

到这里基类就基本完成

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值