浅淡MVP的实战演习,让代码结构更简单~

移动开发 Android
用过MVP的人一定会觉得,在Android中,代码很清晰,不过多了很多类。对于大多数人而言,在看MVP的Demo的时候,一眼便是慢慢的nice,然而让自己来写个例子,却很头疼写不出来。但的确MVC模式写起来更加像是顺水推舟。只需要把自己的业务逻辑一股脑的放进Activity就成功完事儿。

前言

讲道理,这次是真的笔者很久都没有更新blog了,主要最近维护的框架问题也是层出不穷,而且对技术交流群的解答也让我身心疲惫,所以在这里跟关注我的人说声抱歉,没有定期给你们带来福利,那么这里就给大家带来一个重磅福利:爱吖妹纸——Retrofit & RxJava & MVP & Butterknife 的完整App.

讲到最近让我身心疲惫的问题解答,无疑是让我在开源的路上越走越远,虽然我不是技术大牛,却依然被一些很简单的问题轮番轰炸,其实笔者的内心真的是拒绝的。不得不说,写给技术群内的你和群主,为什么你提问,而总没人回你!写的挺好。

概述

废话也不多说,对于MVP(Model View Presenter),我相信大多数人都能说出一些的,“MVC的演化版本”,“让Model和View完全解耦”等等,但用过MVP的人一定会觉得,在Android中,代码很清晰,不过多了很多类。对于大多数人而言,在看MVP的Demo的时候,一眼便是慢慢的nice,然而让自己来写个例子,却很头疼写不出来。但的确MVC模式写起来更加像是顺水推舟。只需要把自己的业务逻辑一股脑的放进Activity就成功完事儿。

不得不说,之前我们项目中的确也是用的MVC在编写的。很简单的会发现随便一个Activity代码都是几百上千行,甚至还有一万行以上的。看起来的确那么一回事儿,但是细想这个View对于布局文件,其实能做的事情特别少,实际上关于该布局文件中的数据绑定的操作,事件处理的操作都在Activity中,造成了Activity既想View又像Controller,鄙弃代码上的不美观来说,对于后面的阅读代码真的是吃力。

不信?你瞧瞧。

也许业务逻辑比较简单的功能用MVC没什么,但是想没想过,如果你产品后面改需求怎么办?是的,你接受产品需求的强奸,但还是只有忍辱偷生。在日渐复杂的业务逻辑上,你的Activity和Fragment代码越来越多,最终导致代码爆炸,难以维护。

网上浏览一圈,发现讲MVP的文章比比皆是,可见MVP的欢迎度,但大多数文章都只是讲理论,稍微好点的会附带一个简单的登录的Demo。然而,一个简单的demo很难让初次接触MVP模式的人掌握它的使用。所以爱吖妹纸应运而生。

什么是MVP

当然不能跑题,前面对 MVP 做了简单的概述,下面还是用一个简单的图表示一下。

 

如上图所示,在项目中 View 和 Model 并不直接交互,而是使用 Presenter 作为 View 和 Model 之间的桥梁。其中 Presenter 中同时持有 View 层以及 Model 层的 Interface 的引用,而 View 层持有 Presenter 层 Interface 的引用,当 View 层某个页面需要展示某些数据的时候,首先会调用Presenter 层的某个接口,然后 Presenter 层会调用 Model 层请求数据,当 Model 层数据加载成功之后会调用 Presenter 层的回调方法通知 Presenter 层数据加载完毕,*** Presenter 层再调用 View 层的接口将加载后的数据展示给用户。这就是 MVP 模式的核心过程。

这样分层的好处就是大大减少了Model与View层之间的耦合度。一方面可以使得View层和Model层单独开发与测试,互不依赖。另一方面Model层可以封装复用,可以极大的减少代码量。当然,MVP还有其他的一些优点,这里不再赘述。

功能展示

这里就给大家随便看看干货板块的功能吧。

布局相当简单。

  1. <android.support.v4.widget.SwipeRefreshLayout 
  2.     xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     xmlns:app="http://schemas.android.com/apk/res-auto" 
  4.     android:id="@+id/swipe_refresh_layout" 
  5.     android:layout_width="match_parent" 
  6.     android:layout_height="match_parent"
  7.  
  8.     <com.nanchen.aiyagirl.widget.RecyclerViewWithFooter.RecyclerViewWithFooter 
  9.         android:id="@+id/recyclerView" 
  10.         android:layout_width="match_parent" 
  11.         android:layout_height="match_parent"/> 
  12.  
  13. </android.support.v4.widget.SwipeRefreshLayout>  

干货模块,也就是一个Fragment,里面有一个RecyclerView,支持下拉刷新和上拉加载数据。所以我们的 Presenter 和 View 只需要定义一下简单的方法。

1)加载数据的过程中显示加载的进度条;

2)加载数据成功提醒 Adapter 刷新数据;

3)加载失败谈窗提醒用户相关信息;

4)加载结束隐藏进度条;

  1. public interface CategoryContract {     
  2.     interface ICategoryView extends BaseView{  
  3.         void getCategoryItemsFail(String failMessage);         
  4.         void setCategoryItems(CategoryResult categoryResult);         
  5.         void addCategoryItems(CategoryResult categoryResult);         
  6.         void showSwipeLoading();         
  7.         void hideSwipeLoading();         
  8.         void setLoading();         
  9.         String getCategoryName();         
  10.         void noMore(); 
  11.     }    interface ICategoryPresenter extends BasePresenter{         
  12.         void getCategoryItems(boolean isRefresh); 
  13.     } 
  14.  

编写 Presenter 实现类。

  1. public class CategoryPresenter implements ICategoryPresenter {     
  2. private ICategoryView mCategoryICategoryView;     
  3. private int mPage = 1;     
  4. private Subscription mSubscription;     
  5. public CategoryPresenter(ICategoryView androidICategoryView) { 
  6.         mCategoryICategoryView = androidICategoryView; 
  7.     }     
  8.     @Override 
  9.     public void subscribe() { 
  10.         getCategoryItems(true); 
  11.     }     
  12.     @Override 
  13.     public void unSubscribe() {         
  14.         if (mSubscription != null  && !mSubscription.isUnsubscribed()){ 
  15.             mSubscription.unsubscribe(); 
  16.         } 
  17.     }    @Override 
  18.     public void getCategoryItems(final boolean isRefresh) {         
  19.         if (isRefresh) { 
  20.             mPage = 1; 
  21.             mCategoryICategoryView.showSwipeLoading(); 
  22.         } else { 
  23.             mPage++; 
  24.         } 
  25.         mSubscription = NetWork.getGankApi() 
  26.                 .getCategoryData(mCategoryICategoryView.getCategoryName(), GlobalConfig.CATEGORY_COUNT,mPage) 
  27.                 .subscribeOn(Schedulers.io()) 
  28.                 .observeOn(AndroidSchedulers.mainThread()) 
  29.                 .subscribe(new Observer<CategoryResult>() {                     
  30.                     @Override 
  31.                     public void onCompleted() { 
  32.  
  33.                     }                     
  34.                     @Override 
  35.                     public void onError(Throwable e) { 
  36.                         mCategoryICategoryView.hideSwipeLoading(); 
  37.                         mCategoryICategoryView.getCategoryItemsFail(mCategoryICategoryView.getCategoryName()+" 列表数据获取失败!"); 
  38.                     }                     
  39.                     @Override 
  40.                     public void onNext(CategoryResult categoryResult) {                         
  41.                         if (isRefresh){ 
  42.                             mCategoryICategoryView.setCategoryItems(categoryResult); 
  43.                             mCategoryICategoryView.hideSwipeLoading(); 
  44.                             mCategoryICategoryView.setLoading(); 
  45.                         }else { 
  46.                             mCategoryICategoryView.addCategoryItems(categoryResult); 
  47.                         } 
  48.                     } 
  49.                 }); 
  50.     } 
  51.  

编写Adapter,用于展示数据。

  1. class CategoryRecyclerAdapter extends CommonRecyclerAdapter<CategoryResult.ResultsBean> implements  
  2. ListenerWithPosition.OnClickWithPositionListener<CommonRecyclerHolder>{ 
  3.  
  4.     CategoryRecyclerAdapter(Context context) {         
  5.         super(context, null, R.layout.item_category); 
  6.     }    @Override 
  7.     public void convert(CommonRecyclerHolder holder, ResultsBean resultsBean) {         
  8.         if (resultsBean != null) {             
  9.         ImageView imageView = holder.getView(R.id.category_item_img);             
  10.         if (ConfigManage.INSTANCE.isListShowImg()) { // 列表显示图片 
  11.                 imageView.setVisibility(View.VISIBLE);                 
  12.             String quality = "";                 
  13.             if (resultsBean.images != null && resultsBean.images.size() > 0) { 
  14.                     switch (ConfigManage.INSTANCE.getThumbnailQuality()) {                         
  15.                         case 0: // 原图 
  16.                             quality = "";                             
  17.                             break;                         
  18.                         case 1: // 
  19.                             quality = "?imageView2/0/w/400";                             
  20.                             break;                         
  21.                         case 2: 
  22.                             quality = "?imageView2/0/w/190";                             
  23.                             break; 
  24.                     }                     
  25.                     Glide.with(mContext) 
  26.                             .load(resultsBean.images.get(0) + quality) 
  27.                             .placeholder(R.mipmap.image_default) 
  28.                             .error(R.mipmap.image_default) 
  29.                             .into(imageView); 
  30.                 } else { // 列表不显示图片 
  31.                     Glide.with(mContext).load(R.mipmap.image_default).into(imageView); 
  32.                 } 
  33.             } else { 
  34.                 imageView.setVisibility(View.GONE); 
  35.             } 
  36.  
  37.             holder.setTextViewText(R.id.category_item_desc, resultsBean.desc == null ? "unknown" : resultsBean.desc); 
  38.             holder.setTextViewText(R.id.category_item_author, resultsBean.who == null ? "unknown" : resultsBean.who); 
  39.             holder.setTextViewText(R.id.category_item_time, TimeUtil.dateFormat(resultsBean.publishedAt)); 
  40.             holder.setTextViewText(R.id.category_item_src, resultsBean.source == null ? "unknown" : resultsBean.source); 
  41.             holder.setOnClickListener(this, R.id.category_item_layout); 
  42.         } 
  43.     }    @Override 
  44.     public void onClick(View v, int position, CommonRecyclerHolder holder) { 
  45.         //Toasty.info(mContext,"跳转到相应网页!", Toast.LENGTH_SHORT,true).show(); 
  46.         Intent intent = new Intent(mContext, WebViewActivity.class); 
  47.         intent.putExtra(WebViewActivity.GANK_TITLE, mData.get(position).desc); 
  48.         intent.putExtra(WebViewActivity.GANK_URL, mData.get(position).url); 
  49.         mContext.startActivity(intent); 
  50.     } 
  51.  

***当然是 Fragment。

  1. public class CategoryFragment extends BaseFragment implements ICategoryView, OnRefreshListener, OnLoadMoreListener {     
  2. public static final String CATEGORY_NAME = "com.nanchen.aiyagirl.module.category.CategoryFragment.CATEGORY_NAME";     
  3. @BindView(R.id.recyclerView) 
  4.     RecyclerViewWithFooter mRecyclerView;     
  5.     @BindView(R.id.swipe_refresh_layout) 
  6.     SwipeRefreshLayout mSwipeRefreshLayout;     
  7.         private String categoryName;     
  8.         private CategoryRecyclerAdapter mAdapter;     
  9.         private ICategoryPresenter mICategoryPresenter;     
  10.         public static CategoryFragment newInstance(String mCategoryName) { 
  11.         CategoryFragment categoryFragment = new CategoryFragment(); 
  12.         Bundle bundle = new Bundle(); 
  13.         bundle.putString(CATEGORY_NAME, mCategoryName); 
  14.         categoryFragment.setArguments(bundle);         
  15.         return categoryFragment; 
  16.     }    @Override 
  17.     protected int getContentViewLayoutID() {         
  18.         return R.layout.fragment_category; 
  19.     }    @Override 
  20.     protected void init() { 
  21.         mICategoryPresenter = new CategoryPresenter(this); 
  22.         categoryName = getArguments().getString(CATEGORY_NAME); 
  23.         mSwipeRefreshLayout.setOnRefreshListener(this); 
  24.         mAdapter = new CategoryRecyclerAdapter(getActivity()); 
  25.         mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); 
  26.         mRecyclerView.addItemDecoration(new RecyclerViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL)); 
  27.         mRecyclerView.setAdapter(mAdapter); 
  28.         mRecyclerView.setOnLoadMoreListener(this); 
  29.         mRecyclerView.setEmpty(); 
  30.         mICategoryPresenter.subscribe(); 
  31.     }    @Override 
  32.     public void onDestroy() {         
  33.         super.onDestroy();         
  34.         if (mICategoryPresenter != null) { 
  35.             mICategoryPresenter.unSubscribe(); 
  36.         } 
  37.     }    @Override 
  38.     public void onRefresh() { 
  39.         mICategoryPresenter.getCategoryItems(true); 
  40.     }    @Override 
  41.     public void onLoadMore() { 
  42.         mICategoryPresenter.getCategoryItems(false); 
  43.     }    @Override 
  44.     public void getCategoryItemsFail(String failMessage) {         
  45.         if (getUserVisibleHint()) { 
  46.             Toasty.error(this.getContext(), failMessage).show(); 
  47.         } 
  48.     }    @Override 
  49.     public void setCategoryItems(CategoryResult categoryResult) { 
  50.         mAdapter.setData(categoryResult.results); 
  51.     }    @Override 
  52.     public void addCategoryItems(CategoryResult categoryResult) { 
  53.         mAdapter.addData(categoryResult.results); 
  54.  
  55.     }    @Override 
  56.     public void showSwipeLoading() { 
  57.         mSwipeRefreshLayout.setRefreshing(true); 
  58.     }    @Override 
  59.     public void hideSwipeLoading() { 
  60.         mSwipeRefreshLayout.setRefreshing(false); 
  61.     }    @Override 
  62.     public void setLoading() { 
  63.         mRecyclerView.setLoading(); 
  64.     }    @Override 
  65.     public String getCategoryName() {         
  66.         return this.categoryName; 
  67.     }    @Override 
  68.     public void noMore() { 
  69.         mRecyclerView.setEnd("没有更多数据"); 
  70.     } 
  71.  

项目截图

还是给大家看看项目截图,以免大家心慌。

    

 

结束语

爱吖妹纸是运用 MVP,Retrofit,RxJava 等主流框架整合的干货 App,项目资源来源于代码家的干货集中营。代码量不多,但基本涉及了各个方面,界面采用design风格,所以也是学习design的良药。作者也是希望继续在开源路上越走越远,还请大家支持。

责任编辑:庞桂玉 来源: 安卓巴士Android开发者门户
相关推荐

2010-07-22 14:59:24

SQL Server

2010-08-06 13:26:29

DB2建立databa

2021-08-02 19:39:51

网络测试路由器

2010-06-07 14:57:57

2010-05-27 16:55:23

操作MySQL

2010-08-17 11:35:00

2010-08-03 16:54:10

DB2 9.5

2010-06-18 09:08:29

SQL Server

2012-09-25 09:28:36

程序员代码代码整洁

2020-07-15 08:37:11

JavaScript开发技术

2022-10-31 07:09:15

拷贝代码项目

2012-06-20 13:36:42

Surface平板

2020-05-07 10:18:06

JavaScript前端技术

2019-07-10 10:20:36

前端用户体验javascript

2019-04-04 14:05:20

consolejs前端

2022-08-29 18:34:46

Pythonsubprocess系统

2023-12-01 16:00:48

Python结构化模式

2021-07-24 13:16:31

Android 代码操作系统

2015-05-20 12:50:42

C#开发抽象增删改
点赞
收藏

51CTO技术栈公众号