安卓MVP框架

邹学民
2023-12-01

地址:GitHub地址

封装的还是挺多东西的,我也就不一一说了。可以去仓库看看,直接看源码吧。

BaseMvpActivity:

public abstract class BaseMvpActivity<T extends IBaseContract.IBasePresenter> extends AppCompatActivity
        implements IBaseContract.IBaseView, IListener,View.OnClickListener {
    protected T presenter;
    protected Context context;
    /**
     * 进度框
     */
    protected Dialog loadingDialog;
    protected Toast toast;

    /**
     * 确认框
     */
    protected MaterialDialog confirmDialog;
    /**
     * Inquiry对话框
     */
    protected MaterialDialog inquiryDialog;
    private MaterialDialog.SingleButtonCallback confirmCallback = (dialog, which) -> onConfirmCallback();
    private MaterialDialog.SingleButtonCallback cancelCallback = (dialog, which) -> onCancelCallback();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        presenter = createPresenter();
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        initViewAndData(savedInstanceState);

        loadingDialog = DialogHelper.loadingDialog(context);
        inquiryDialog = DialogHelper.inquiryDialog(context, this);
        confirmDialog = DialogHelper.confirmDialog(context, confirmCallback, cancelCallback);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestory();
    }

    @Override
    protected void onStop() {
        super.onStop();
        presenter.onStop();
    }

    @Override
    public void showError(String msg) {
        Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoadingWithMessage(String loadingText) {
        if (null != loadingDialog && !loadingDialog.isShowing()) {
            runOnUiThread(() -> {
                if (null != loadingDialog.getWindow()) {
                    TextView tvLoad = loadingDialog.getWindow().findViewById(R.id.tv_load_dialog);
                    tvLoad.setText(loadingText);
                    loadingDialog.show();
                }
            });
        }
    }

    @Override
    public void showLoading() {
        if (null != loadingDialog && !loadingDialog.isShowing()) {
            runOnUiThread(() -> loadingDialog.show());
        }
    }

    @Override
    public void showContent(String message,int duration) {
        runOnUiThread(() -> {
            if (toast == null) {
                toast = Toast.makeText(context, message, duration);
            }
            toast.setText(message);
            toast.setDuration(duration);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        });
    }

    @Override
    public void dismissLoading() {
        if (null != loadingDialog && loadingDialog.isShowing()) {
            runOnUiThread(() -> loadingDialog.dismiss());
        }
    }


    @Override
    public void showInquiryDialog(String message) {
        if (null != inquiryDialog && !inquiryDialog.isShowing()) {
            runOnUiThread(() -> {
                if (null != inquiryDialog.getCustomView()) {
                    TextView tvMessage = inquiryDialog.getCustomView().findViewById(R.id.dialog_common_inquiry_tv_message);
                    tvMessage.setText(message);
                    inquiryDialog.show();
                } else {
                    Log.e(this.getClass().getName(),"inquiry dialog custom view is null.");
                }
            });
        }
    }

    @Override
    public void showConfirmDialog(String title, String message, String buttonConfirm, String buttonCancel) {
        if(confirmDialog != null && !confirmDialog.isShowing()){
            runOnUiThread(() -> {
                MaterialDialog.Builder builder = confirmDialog.getBuilder();
                if (StringUtils.isNotEmpty(title)) {
                    builder.title(title);
                }
                if (StringUtils.isNotEmpty(message)) {
                    builder.content(message);
                }
                if (StringUtils.isNotEmpty(buttonConfirm)) {
                    builder.positiveText(buttonConfirm);
                }
                if (StringUtils.isNotEmpty(buttonCancel)) {
                    builder.negativeText(buttonCancel);
                }
                builder.show();
            });
        }
    }


    @Override
    public void onClick(View v) {
        if (R.id.dialog_common_inquiry_btn_confirm == v.getId()) {
            onInquiryConfirm();
        } else if (R.id.dialog_common_inquiry_btn_cancel == v.getId()) {
            onInquiryCancel();
        }
    }

    @Override
    public void onInquiryConfirm() {
        if (null != inquiryDialog && inquiryDialog.isShowing()) {
            inquiryDialog.dismiss();
        }
    }

    @Override
    public void onInquiryCancel() {
        if (null != inquiryDialog && inquiryDialog.isShowing()) {
            inquiryDialog.dismiss();
        }
    }


    @Override
    public void onConfirmCallback() {
        if (null != confirmDialog && confirmDialog.isShowing()) {
            confirmDialog.dismiss();
        }
    }

    @Override
    public void onCancelCallback() {
        if (null != confirmDialog && confirmDialog.isShowing()) {
            confirmDialog.dismiss();
        }
    }

    /**
     * 初始化数据
     * @param savedInstanceState
     */
    protected abstract void initViewAndData(Bundle savedInstanceState);

    /**
     * 注入P层对象
     * @return
     */
    protected abstract T createPresenter();

    /**
     * 设置布局文件ID
     * @return
     */
    protected abstract int getLayoutId();
}

BasePresenter:

package com.jzh.mvp.mvp.base;


import com.jzh.mvp.base.BaseApplication;
import com.jzh.mvp.injection.component.AppComponent;

import java.lang.ref.WeakReference;

/**
 * <p></p>
 * <p></p>
 *
 * @author jinzhenhua
 * @version 1.0  ,create at:2020/5/26 17:21
 */
public class BasePresenter<T extends IBaseContract.IBaseView,P extends IBaseContract.IBaseModel> implements IBaseContract.IBasePresenter {
    // 防止 Activity 不走 onDestory() 方法,所以采用弱引用来防止内存泄漏
    private WeakReference<T> mViewRef;
    protected P model;
    protected AppComponent mAppComponent;

    public BasePresenter(T view){
        mViewRef = new WeakReference<T>(view);
        init();
    }

    @Override
    public void onStop() {
        if(model != null){
            //清除调用中的接口
            model.onStop();
        }
    }

    @Override
    public void onDestory() {
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
        if(model != null){
            //清除调用中的接口
            model.onDestory();
            model = null;
        }
    }

    @Override
    public boolean isViewAttach() {
        return mViewRef != null;
    }

    public T getView() {
        return mViewRef.get();
    }

    /**
     * 获取回调接口的实现,经过一层封装,默认显示加载进度框
     * @param callback
     * @return
     */
    public ApiCallbackWrapper getApiCallBackWithLoading(HttpResponseListener callback){
        return new ApiCallbackWrapper(callback,true);
    }

    /**
     * 拦截回调方法,中间插入loading操作
     * @param <T>
     */
    protected class ApiCallbackWrapper<T> implements HttpResponseListener<T>{
        private HttpResponseListener callback;
        private boolean showLoading;

        public ApiCallbackWrapper(HttpResponseListener callback,boolean showLoading){
            this.callback = callback;
            this.showLoading = showLoading;
            if(showLoading){
                getView().showLoading();
            }
        }

        @Override
        public void onSuccess(Object tag, T o) {
            callback.onSuccess(tag,o);
            if(showLoading){
                getView().dismissLoading();
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            callback.onFailure(throwable);
            if(showLoading){
                getView().dismissLoading();
            }
        }
    }

    //初始化注入类
    protected void init() {
        mAppComponent = BaseApplication.application.getmAppComponent();
    }
}

BaseModel:

package com.jzh.mvp.mvp.base;

import com.jzh.mvp.http.HttpRespondData;
import com.jzh.mvp.http.HttpUtils;
import com.jzh.mvp.http.RxTransformer;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;

/**
 * <p></p>
 * <p></p>
 *
 * @author jinzhenhua
 * @version 1.0  ,create at:2020/5/26 17:21
 */
public class BaseModel implements IBaseContract.IBaseModel {

    private CompositeDisposable disposableWhenStop = new CompositeDisposable();
    private CompositeDisposable disposableWhenDestory = new CompositeDisposable();
    private RxTransformer api = new RxTransformer();

    @Override
    public void onStop() {
        //解除订阅
        disposableWhenStop.dispose();
        disposableWhenStop.clear();
    }

    @Override
    public void onDestory() {
        //解除订阅
        disposableWhenStop.dispose();
        disposableWhenDestory.clear();
    }

    /**
     * 发送网络请求,页面stop时会解除绑定
     *
     * @param observable
     * @param callback
     * @param <T>
     */
    protected <T> void sendRequestUntilStop(@NonNull Observable<HttpRespondData<T>> observable, final HttpResponseListener<T> callback) {
        disposableWhenStop.add(api.apiRequest(observable,callback));
    }

    /**
     * 发送网络请求,页面destory时会解除绑定
     *
     * @param observable
     * @param callback
     * @param <T>
     */
    protected <T> void sendRequestUntilDestory(@NonNull Observable<HttpRespondData<T>> observable, final HttpResponseListener<T> callback) {
        disposableWhenDestory.add(api.apiRequest(observable,callback));
    }


    protected  <T> T getService(Class<T> clazz){
        return HttpUtils.getRetrofit().create(clazz);
    }



}

有什么不足或者写的不好的地方,或是有什么疑问都欢迎大伙留言提出。

 类似资料: