MVP模式下面基类的抽取

一.都说好的封装能省不少事情,也能很好的解决代码的耦合性,减少后期维护项目的成本,好了废话不多说了我们来看看代码
1.这是封装好的BaseActivity

public abstract class BaseActivity<T extends IPresenter> extends AppCompatActivity {
    protected T mPresenter;
    private LoadingDialog loadingDialog;
    protected AppCompatActivity mActivity;

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        boolean animition = intent.getBooleanExtra("animition", true);
        if (animition) {
            overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_right_reman);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        mActivity = this;
        AppManager.getAppManager().addActivity(this);
        mPresenter = getPresenter();
        if (getToolBar() != null) {
            getToolBar().setTitle("");
            setSupportActionBar(getToolBar());
        }
        initData();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }

        onClick();

        if (!this.getClass().getSimpleName().equals("MainActivity") && !this.getClass().getSimpleName().equals("SearchActivity")
                &&!this.getClass().getSimpleName().equals("InviteActivity")
                &&!this.getClass().getSimpleName().equals("WillActivity")) {

            setDrawable(0);
        }
        if (getToolBar() != null) {
            getToolBar().setNavigationOnClickListener(view -> finish());
        }
    }

    @Override
    public void finish() {
        super.finish();
        boolean animition = getIntent().getBooleanExtra("animition", true);
        if (animition) {
            overridePendingTransition(0, R.anim.base_slide_right_out);
        }
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        boolean animition = intent.getBooleanExtra("animition", true);
        if (animition) {
            overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_right_reman);
        }

    }

    @Override
    protected void onStart() {
        if (getToolBar() != null){
            getToolBar().setNavigationIcon(R.mipmap.home_page_details_return);
        }
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unSubcrible();
        }
        dismissLoadingDialog();
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0, R.anim.base_slide_right_out);
    }


    protected abstract T getPresenter();

    protected abstract int getLayoutId();

    protected abstract void initData();

    protected abstract void onClick();

    protected abstract Toolbar getToolBar();

    protected void setDrawable(int drawable) {
        if (drawable != 0) {
            getToolBar().setNavigationIcon(getResources().getDrawable(drawable));
        } else {
            getToolBar().setNavigationIcon(getResources().getDrawable(R.mipmap.ic_back));
        }
    }

    protected void logD(String log) {
        LogUtils.d(this, log);
    }

    protected void logE(String log) {
        LogUtils.e(this, log);
    }

    protected void toaskMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    protected void showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        }
        loadingDialog.show();
    }

    protected void dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShow()) {
            loadingDialog.close();
        }
    }
}

上面封装的东西很多了,各位可以视情况减少或添加
2.下面是fragment的封装

public abstract class BaseFragment<T extends IPresenter> extends Fragment {
    protected T mPresenter;
    protected View view;
    private LoadingDialog loadingDialog;
    protected Context context;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(getLayoutId(), container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, view);
        context = getActivity();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPresenter = getPresenter();
        initData();
        onClick();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (mPresenter != null)
            mPresenter.unSubcrible();
    }

    protected abstract T getPresenter();

    protected abstract int getLayoutId();

    protected abstract void initData();

    protected abstract void onClick();

    protected void logD(String log) {
        LogUtils.d(context, log);
    }

    protected void logE(String log) {
        LogUtils.e(context, log);
    }

    protected void toaskMsg(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    protected void showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(context);
        }
        loadingDialog.show();
    }

    protected void dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShow()) {
            loadingDialog.close();
        }
    }
    protected boolean getLogin(){
        return MvpContactApplication.getInstance().appData.getLogin();
    }
}

3.下面是presenter的封装

public class BasePresenter<T extends IBaseView> implements IPresenter {
    private T mView;
    protected CompositeDisposable compositeSubscription;
    private LoadingDialog loadingDialog;

    public BasePresenter(T view) {
        this.mView = view;
    }

    protected void unSubscribe() {
        if (compositeSubscription != null) {
            compositeSubscription.dispose();
        }
    }

    public void showDialog() {
        loadingDialog = new LoadingDialog((Activity) mView.getMyContext());
        loadingDialog.show();
    }

    public void closeDialog() {
        if (loadingDialog != null) {
            loadingDialog.close();
        }
    }

    protected void addSubscribe(Disposable subscription) {
        if (compositeSubscription == null) {
            compositeSubscription = new CompositeDisposable();
        }
        compositeSubscription.add(subscription);
    }

    protected Context getContext() {
        return mView.getMyContext();
    }

    @Override
    public void unSubcrible() {
        this.mView = null;
        unSubscribe();
    }
}

4.IBaseView里面一个接口

public interface IBaseView {
    Context getMyContext();
    void error();
}

5.IPresenter的接口

public interface IPresenter {
    void unSubcrible();
}

基类的封装因人而异,也仅仅给大家提供一个思路,具体设计得看需求的分析,欢迎各位技术大牛吐槽切磋,我虚心接受。
技术交流qq:1129126470
WeChat:ym1129126470,不吝赐教 转载请注明出处,尊重知识。

好的,以下是一个简单的 MVP 框架,包含 Okhttp+Retrofit 网络封装,Base 基类抽取以及 APPLocation 的代码: 1. 首先创建一个 BaseView 接口,定义一些公共的 UI 操作方法: ```java public interface BaseView { void showLoading(); void hideLoading(); void showError(String error); } ``` 2. 接着创建一个 BasePresenter 类,定义一些公共的 Presenter 操作方法: ```java public class BasePresenter<V extends BaseView> { private WeakReference<V> mViewRef; public void attachView(V view) { mViewRef = new WeakReference<>(view); } public void detachView() { if (mViewRef != null) { mViewRef.clear(); mViewRef = null; } } public boolean isViewAttached() { return mViewRef != null && mViewRef.get() != null; } public V getView() { return mViewRef.get(); } public void checkViewAttached() { if (!isViewAttached()) throw new RuntimeException("Please call attachView() before requesting data to the Presenter"); } } ``` 3. 创建一个 BaseActivity 类,作为所有 Activity 的基类,包含一些公共的操作: ```java public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements BaseView { protected P mPresenter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutId()); mPresenter = createPresenter(); if (mPresenter != null) { mPresenter.attachView(this); } initView(); } @Override protected void onDestroy() { super.onDestroy(); if (mPresenter != null) { mPresenter.detachView(); } } protected abstract int getLayoutId(); protected abstract P createPresenter(); protected abstract void initView(); } ``` 4. 接着创建一个 BaseFragment 类,作为所有 Fragment 的基类,也包含一些公共的操作: ```java public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements BaseView { protected P mPresenter; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPresenter = createPresenter(); if (mPresenter != null) { mPresenter.attachView(this); } } @Override public void onDestroy() { super.onDestroy(); if (mPresenter != null) { mPresenter.detachView(); } } protected abstract P createPresenter(); } ``` 5. 创建一个 AppApplication 类,作为整个应用程序的入口,包含一些公共的配置信息和初始化操作: ```java public class AppApplication extends Application { private static AppApplication sInstance; @Override public void onCreate() { super.onCreate(); sInstance = this; // 初始化网络请求 RetrofitClient.getInstance().init(this); } public static AppApplication getInstance() { return sInstance; } } ``` 6. 创建一个 RetrofitClient 类,用于封装 Okhttp+Retrofit 网络请求: ```java public class RetrofitClient { private static final String TAG = "RetrofitClient"; private static final int DEFAULT_TIMEOUT = 30; private Retrofit mRetrofit = null; private OkHttpClient mOkHttpClient = null; private RetrofitClient() {} public static RetrofitClient getInstance() { return SingletonHolder.INSTANCE; } private static class SingletonHolder { private static final RetrofitClient INSTANCE = new RetrofitClient(); } public void init(Context context) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); mOkHttpClient = new OkHttpClient.Builder() .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .addInterceptor(loggingInterceptor) .addInterceptor(new TokenInterceptor()) .build(); mRetrofit = new Retrofit.Builder() .baseUrl(ApiService.BASE_URL) .client(mOkHttpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } public ApiService getApiService() { return mRetrofit.create(ApiService.class); } } ``` 7. 创建一个 ApiService 接口,定义所有的网络请求接口: ```java public interface ApiService { String BASE_URL = "https://www.example.com/"; @POST("login") Observable<BaseResponse<User>> login(@Query("username") String username, @Query("password") String password); } ``` 8. 最后,我们可以创建一个 LoginPresenter 类,来处理登录相关的业务逻辑: ```java public class LoginPresenter extends BasePresenter<LoginContract.View> implements LoginContract.Presenter { private ApiService mApiService; public LoginPresenter() { mApiService = RetrofitClient.getInstance().getApiService(); } @Override public void login(String username, String password) { checkViewAttached(); getView().showLoading(); mApiService.login(username, password) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<BaseResponse<User>>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(BaseResponse<User> userBaseResponse) { getView().hideLoading(); if (userBaseResponse.getCode() == 0) { getView().loginSuccess(userBaseResponse.getData()); } else { getView().showError(userBaseResponse.getMsg()); } } @Override public void onError(Throwable e) { getView().hideLoading(); getView().showError(e.getMessage()); } @Override public void onComplete() { } }); } } ``` 以上就是一个简单的 MVP 框架的实现,您可以根据自己的需求进行修改和扩展。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值