Android如何简单封装一个MVP基类
更新时间:2023-07-17前言
在Android开发中,采用MVP架构是很普遍的选择。MVP即Model-View-Presenter,它是一种设计模式,可以有效地减少代码冗余,提高代码可重用性和可维护性。在MVP中,Presenter是连接View和Model的桥梁,而View只用关心UI展示和用户操作,Model只用关心数据处理和网络请求。为了更好的实现Presenter和View之间的解耦,我们可以封装一个MVP基类,方便后续的开发。MVP基类封装步骤
封装一个MVP基类的步骤主要包括以下几点:
1. 封装BaseView基类
BaseView是View的基类,用来定义通用的UI展示逻辑,比如显示加载中、显示错误信息等。以下是BaseView的示例代码:
public interface BaseView { void showLoading(); void hideLoading(); void showError(String error); }
2. 封装BasePresenter基类
BasePresenter是Presenter的基类,用来定义通用的UI逻辑和业务逻辑,比如网络请求、数据处理等。以下是BasePresenter的示例代码:
public abstract class BasePresenter{ protected V mView; public BasePresenter(V view) { mView = view; } public abstract void start(); public void onDestroy() { mView = null; } }
3. 封装BaseActivity和BaseFragment基类
BaseActivity和BaseFragment是Activity和Fragment的基类,用来定义通用的UI展示和用户操作逻辑,比如findViewById、setContentView、onClick等。以下是BaseActivity和BaseFragment的示例代码:
public abstract class BaseActivityextends AppCompatActivity implements BaseView { protected P mPresenter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutId()); initView(); mPresenter = createPresenter(); mPresenter.start(); } protected abstract int getLayoutId(); protected abstract void initView(); protected abstract P createPresenter(); @Override protected void onDestroy() { super.onDestroy(); mPresenter.onDestroy(); } @Override public void showLoading() { //显示加载中UI } @Override public void hideLoading() { //隐藏加载中UI } @Override public void showError(String error) { //展示错误信息UI } } public abstract class BaseFragment
extends Fragment implements BaseView { protected View mView; protected P mPresenter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mView = inflater.inflate(getLayoutId(), container, false); initView(); initData(); mPresenter = createPresenter(); mPresenter.start(); return mView; } protected abstract int getLayoutId(); protected abstract void initView(); protected abstract void initData(); protected abstract P createPresenter(); @Override public void showLoading() { //显示加载中UI } @Override public void hideLoading() { //隐藏加载中UI } @Override public void showError(String error) { //展示错误信息UI } }