Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> MVP模式在Android項目中的使用,mvp模式android項目

MVP模式在Android項目中的使用,mvp模式android項目

編輯:關於android開發

MVP模式在Android項目中的使用,mvp模式android項目


  以前在寫項目的時候,沒有過多考慮架構模式的問題,因為之前一直做J2EE開發,而J2EE都是采用MVC模式進行開發的,所以在搭建公司項目的時候,也是使用類似MVC的架構(嚴格來講,之前的項目還算不上MVC模式,只是簡單將網絡請求與界面分離,然後通過Handle通知更新界面)。這種寫法,在後面隨著項目越來越大,Activty或者Fragment中代碼也會越來越多,導致項目的維護變的越來越復雜。所以需要另外一種架構模式來解決這個問題,在網上浏覽了一圈,發現適合Android開發的架構模式非MVP莫屬了。

  網上一搜,講MVP模式的文章比比皆是。但是大多都是講理論,稍微好點的會附帶一個簡單的登錄的demo。一個簡單的demo很難讓初次接觸MVP模式的人掌握它的使用。所以我決定寫一個稍微復雜一點的新聞客戶端SimpleNews(當然只是相對登錄的demo)來展示MVP在具體項目中的使用。另外SimpleNews還使用了Material Design,也是學習Material Design的一個好Demo。

  好了,切入正文吧。先講一下MVP的概念。

什麼是MVP

  MVP是模型(Model)、視圖(View)、主持人(Presenter)的縮寫,分別代表項目中3個不同的模塊。

  模型(Model):負責處理數據的加載或者存儲,比如從網絡或本地數據庫獲取數據等;

  視圖(View):負責界面數據的展示,與用戶進行交互;

  主持人(Presenter):相當於協調者,是模型與視圖之間的橋梁,將模型與視圖分離開來。

  如下圖所示,View與Model並不直接交互,而是使用Presenter作為View與Model之間的橋梁。其中Presenter中同時持有Viwe層以及Model層的Interface的引用,而View層持有Presenter層Interface的引用。當View層某個界面需要展示某些數據的時候,首先會調用Presenter層的某個接口,然後Presenter層會調用Model層請求數據,當Model層數據加載成功之後會調用Presenter層的回調方法通知Presenter層數據加載完畢,最後Presenter層再調用View層的接口將加載後的數據展示給用戶。這就是MVP模式的整個核心過程。

  這樣分層的好處就是大大減少了Model與View層之間的耦合度。一方面可以使得View層和Model層單獨開發與測試,互不依賴。另一方面Model層可以封裝復用,可以極大的減少代碼量。當然,MVP還有其他的一些優點,這裡不再贅述。下面看下MVP模式在具體項目中的使用。

MVP模式在項目中的使用

1、View層

  View層新聞展示模塊的是組件是Fragment,裡面有一個RecyclerView、SwipeRefreshLayout。布局代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/swipe_refresh_widget"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycle_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:paddingTop="@dimen/card_margin">
    </android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>

  新聞列表模塊主要是展示從網絡獲取的新聞列表信息,View層的接口大概需要如下方法:

  (1)加載數據的過程中需要提示“正在加載”的反饋信息給用戶

  (2)加載成功後,將加載得到的數據填充到RecyclerView展示給用戶

  (3)加載成功後,需要將“正在加載”反饋信息取消掉

  (4)若加載數據失敗,如無網絡連接,則需要給用戶提示信息

  根據上面描述,我們將View層的接口定義如下,分別對應上面四個方法:

public interface NewsView {
    void showProgress();
    void addNews(List<NewsBean> newsList);
    void hideProgress();
    void showLoadFailMsg();
}

  在新聞列表Fragment中實現上述接口:

package com.lauren.simplenews.news.widget;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.lauren.simplenews.R;
import com.lauren.simplenews.beans.NewsBean;
import com.lauren.simplenews.commons.Urls;
import com.lauren.simplenews.news.NewsAdapter;
import com.lauren.simplenews.news.presenter.NewsPresenter;
import com.lauren.simplenews.news.presenter.NewsPresenterImpl;
import com.lauren.simplenews.news.view.NewsView;
import com.lauren.simplenews.utils.LogUtils;
import java.util.ArrayList;
import java.util.List;
/**
 * Description : 新聞Fragment
 * Author : lauren
 * Email  : [email protected]
 * Blog   : http://www.liuling123.com
 * Date   : 15/12/13
 */
public class NewsListFragment extends Fragment implements NewsView, SwipeRefreshLayout.OnRefreshListener {
    private static final String TAG = "NewsListFragment";
    private SwipeRefreshLayout mSwipeRefreshWidget;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    private NewsAdapter mAdapter;
    private List<NewsBean> mData;
    private NewsPresenter mNewsPresenter;
    private int mType = NewsFragment.NEWS_TYPE_TOP;
    private int pageIndex = 0;
    public static NewsListFragment newInstance(int type) {
        Bundle args = new Bundle();
        NewsListFragment fragment = new NewsListFragment();
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNewsPresenter = new NewsPresenterImpl(this);
        mType = getArguments().getInt("type");
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_newslist, null);
        mSwipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        mSwipeRefreshWidget.setColorSchemeResources(R.color.primary,
                R.color.primary_dark, R.color.primary_light,
                R.color.accent);
        mSwipeRefreshWidget.setOnRefreshListener(this);
        mRecyclerView = (RecyclerView)view.findViewById(R.id.recycle_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mAdapter = new NewsAdapter(getActivity().getApplicationContext());
        mAdapter.setOnItemClickListener(mOnItemClickListener);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setOnScrollListener(mOnScrollListener);
        onRefresh();
        return view;
    }
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        private int lastVisibleItem;
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
        }
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItem + 1 == mAdapter.getItemCount()
                    && mAdapter.isShowFooter()) {
                //加載更多
                LogUtils.d(TAG, "loading more data");
                mNewsPresenter.loadNews(mType, pageIndex + Urls.PAZE_SIZE);
            }
        }
    };
    private NewsAdapter.OnItemClickListener mOnItemClickListener = new NewsAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            NewsBean news = mAdapter.getItem(position);
            Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
            intent.putExtra("news", news);
            View transitionView = view.findViewById(R.id.ivNews);
            ActivityOptionsCompat options =
                    ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),
                            transitionView, getString(R.string.transition_news_img));
            ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
        }
    };
    @Override
    public void showProgress() {
        mSwipeRefreshWidget.setRefreshing(true);
    }
    @Override
    public void addNews(List<NewsBean> newsList) {
        mAdapter.isShowFooter(true);
        if(mData == null) {
            mData = new ArrayList<NewsBean>();
        }
        mData.addAll(newsList);
        if(pageIndex == 0) {
            mAdapter.setmDate(mData);
        } else {
            //如果沒有更多數據了,則隱藏footer布局
            if(newsList == null || newsList.size() == 0) {
                mAdapter.isShowFooter(false);
            }
            mAdapter.notifyDataSetChanged();
        }
        pageIndex += Urls.PAZE_SIZE;
    }
    @Override
    public void hideProgress() {
        mSwipeRefreshWidget.setRefreshing(false);
    }
    @Override
    public void showLoadFailMsg() {
        if(pageIndex == 0) {
            mAdapter.isShowFooter(false);
            mAdapter.notifyDataSetChanged();
        }
        Snackbar.make(getActivity().findViewById(R.id.drawer_layout), getString(R.string.load_fail), Snackbar.LENGTH_SHORT).show();
    }
    @Override
    public void onRefresh() {
        pageIndex = 0;
        if(mData != null) {
            mData.clear();
        }
        mNewsPresenter.loadNews(mType, pageIndex);
    }
}

2、Model層

  新聞模塊的model主要負責從服務器獲取新聞列表信息,接口代碼如下:

public interface NewsModel {
    void loadNews(String url, int type, NewsModelImpl.OnLoadNewsListListener listener);
    ......
}

  實現如下:

package com.lauren.simplenews.news.model;
import com.lauren.simplenews.beans.NewsBean;
import com.lauren.simplenews.beans.NewsDetailBean;
import com.lauren.simplenews.commons.Urls;
import com.lauren.simplenews.news.NewsJsonUtils;
import com.lauren.simplenews.news.widget.NewsFragment;
import com.lauren.simplenews.utils.OkHttpUtils;
import java.util.List;
/**
 * Description : 新聞業務處理類
 * Author : lauren
 * Email  : [email protected]
 * Blog   : http://www.liuling123.com
 * Date   : 15/12/19
 */
public class NewsModelImpl implements NewsModel {
    /**
     * 加載新聞列表
     * @param url
     * @param listener
     */
    @Override
    public void loadNews(String url, final int type, final OnLoadNewsListListener listener) {
        OkHttpUtils.ResultCallback<String> loadNewsCallback = new OkHttpUtils.ResultCallback<String>() {
            @Override
            public void onSuccess(String response) {
                List<NewsBean> newsBeanList = NewsJsonUtils.readJsonNewsBeans(response, getID(type));
                listener.onSuccess(newsBeanList);
            }
            @Override
            public void onFailure(Exception e) {
                listener.onFailure("load news list failure.", e);
            }
        };
        OkHttpUtils.get(url, loadNewsCallback);
    }
    ......
    /**
     * 獲取ID
     * @param type
     * @return
     */
    private String getID(int type) {
        String id;
        switch (type) {
            case NewsFragment.NEWS_TYPE_TOP:
                id = Urls.TOP_ID;
                break;
            case NewsFragment.NEWS_TYPE_NBA:
                id = Urls.NBA_ID;
                break;
            case NewsFragment.NEWS_TYPE_CARS:
                id = Urls.CAR_ID;
                break;
            case NewsFragment.NEWS_TYPE_JOKES:
                id = Urls.JOKE_ID;
                break;
            default:
                id = Urls.TOP_ID;
                break;
        }
        return id;
    }
    private String getDetailUrl(String docId) {
        StringBuffer sb = new StringBuffer(Urls.NEW_DETAIL);
        sb.append(docId).append(Urls.END_DETAIL_URL);
        return sb.toString();
    }
    public interface OnLoadNewsListListener {
        void onSuccess(List<NewsBean> list);
        void onFailure(String msg, Exception e);
    }
    ......
}

  網絡請求使用開源項目OkHttp,OkHttpUtils是對其的封裝,具體代碼如下:

package com.lauren.simplenews.utils;
import android.os.Handler;
import android.os.Looper;
import com.google.gson.internal.$Gson$Types;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
 * Description : OkHttp網絡連接封裝工具類
 * Author : lauren
 * Email  : [email protected]
 * Blog   : http://www.liuling123.com
 * Date   : 15/12/17
 */
public class OkHttpUtils {
    private static final String TAG = "OkHttpUtils";
    private static OkHttpUtils mInstance;
    private OkHttpClient mOkHttpClient;
    private Handler mDelivery;
    private OkHttpUtils() {
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
        //cookie enabled
        mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
        mDelivery = new Handler(Looper.getMainLooper());
    }
    private synchronized static OkHttpUtils getmInstance() {
        if (mInstance == null) {
            mInstance = new OkHttpUtils();
        }
        return mInstance;
    }
    private void getRequest(String url, final ResultCallback callback) {
        final Request request = new Request.Builder().url(url).build();
        deliveryResult(callback, request);
    }
    private void postRequest(String url, final ResultCallback callback, List<Param> params) {
        Request request = buildPostRequest(url, params);
        deliveryResult(callback, request);
    }
    private void deliveryResult(final ResultCallback callback, Request request) {
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, final IOException e) {
                sendFailCallback(callback, e);
            }
            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String str = response.body().string();
                    if (callback.mType == String.class) {
                        sendSuccessCallBack(callback, str);
                    } else {
                        Object object = JsonUtils.deserialize(str, callback.mType);
                        sendSuccessCallBack(callback, object);
                    }
                } catch (final Exception e) {
                    LogUtils.e(TAG, "convert json failure", e);
                    sendFailCallback(callback, e);
                }
            }
        });
    }
    private void sendFailCallback(final ResultCallback callback, final Exception e) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onFailure(e);
                }
            }
        });
    }
    private void sendSuccessCallBack(final ResultCallback callback, final Object obj) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onSuccess(obj);
                }
            }
        });
    }
    private Request buildPostRequest(String url, List<Param> params) {
        FormEncodingBuilder builder = new FormEncodingBuilder();
        for (Param param : params) {
            builder.add(param.key, param.value);
        }
        RequestBody requestBody = builder.build();
        return new Request.Builder().url(url).post(requestBody).build();
    }
    /**********************對外接口************************/
    /**
     * get請求
     * @param url  請求url
     * @param callback  請求回調
     */
    public static void get(String url, ResultCallback callback) {
        getmInstance().getRequest(url, callback);
    }
    /**
     * post請求
     * @param url       請求url
     * @param callback  請求回調
     * @param params    請求參數
     */
    public static void post(String url, final ResultCallback callback, List<Param> params) {
        getmInstance().postRequest(url, callback, params);
    }
    /**
     * http請求回調類,回調方法在UI線程中執行
     * @param <T>
     */
    public static abstract class ResultCallback<T> {
        Type mType;
        public ResultCallback(){
            mType = getSuperclassTypeParameter(getClass());
        }
        static Type getSuperclassTypeParameter(Class<?> subclass) {
            Type superclass = subclass.getGenericSuperclass();
            if (superclass instanceof Class) {
                throw new RuntimeException("Missing type parameter.");
            }
            ParameterizedType parameterized = (ParameterizedType) superclass;
            return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
        }
        /**
         * 請求成功回調
         * @param response
         */
        public abstract void onSuccess(T response);
        /**
         * 請求失敗回調
         * @param e
         */
        public abstract void onFailure(Exception e);
    }
    /**
     * post請求參數類
     */
    public static class Param {
        String key;
        String value;
        public Param() {
        }
        public Param(String key, String value) {
            this.key = key;
            this.value = value;
        }
    }
}

  將網絡請求進行封裝可以減少很多的代碼量,並且後期如果我不想用okhttp了,想換成其它的庫,修改起來也方便。

3、Presenter層

  View層需要調用Presenter層加載新聞信息,所以Presenter需要提供加載新聞信息的接口:

public interface NewsPresenter {
    void loadNews(int type, int page);
}

  NewsPresenterImpl的構造函數中需要傳入View層的接口對象NewView,並且需要創建一個NewsModel對象。Presenter的具體實現:

package com.lauren.simplenews.news.presenter;
import com.lauren.simplenews.beans.NewsBean;
import com.lauren.simplenews.commons.Urls;
import com.lauren.simplenews.news.model.NewsModel;
import com.lauren.simplenews.news.model.NewsModelImpl;
import com.lauren.simplenews.news.view.NewsView;
import com.lauren.simplenews.news.widget.NewsFragment;
import com.lauren.simplenews.utils.LogUtils;
import java.util.List;
/**
 * Description :
 * Author : lauren
 * Email  : [email protected]
 * Blog   : http://www.liuling123.com
 * Date   : 15/12/18
 */
public class NewsPresenterImpl implements NewsPresenter, NewsModelImpl.OnLoadNewsListListener {
    private static final String TAG = "NewsPresenterImpl";
    private NewsView mNewsView;
    private NewsModel mNewsModel;
    public NewsPresenterImpl(NewsView newsView) {
        this.mNewsView = newsView;
        this.mNewsModel = new NewsModelImpl();
    }
    @Override
    public void loadNews(final int type, final int pageIndex) {
        String url = getUrl(type, pageIndex);
        LogUtils.d(TAG, url);
        //只有第一頁的或者刷新的時候才顯示刷新進度條
        if(pageIndex == 0) {
            mNewsView.showProgress();
        }
        mNewsModel.loadNews(url, type, this);
    }
    /**
     * 根據類別和頁面索引創建url
     * @param type
     * @param pageIndex
     * @return
     */
    private String getUrl(int type, int pageIndex) {
        StringBuffer sb = new StringBuffer();
        switch (type) {
            case NewsFragment.NEWS_TYPE_TOP:
                sb.append(Urls.TOP_URL).append(Urls.TOP_ID);
                break;
            case NewsFragment.NEWS_TYPE_NBA:
                sb.append(Urls.COMMON_URL).append(Urls.NBA_ID);
                break;
            case NewsFragment.NEWS_TYPE_CARS:
                sb.append(Urls.COMMON_URL).append(Urls.CAR_ID);
                break;
            case NewsFragment.NEWS_TYPE_JOKES:
                sb.append(Urls.COMMON_URL).append(Urls.JOKE_ID);
                break;
            default:
                sb.append(Urls.TOP_URL).append(Urls.TOP_ID);
                break;
        }
        sb.append("/").append(pageIndex).append(Urls.END_URL);
        return sb.toString();
    }
    @Override
    public void onSuccess(List<NewsBean> list) {
        mNewsView.hideProgress();
        mNewsView.addNews(list);
    }
    @Override
    public void onFailure(String msg, Exception e) {
        mNewsView.hideProgress();
        mNewsView.showLoadFailMsg();
    }
}

  當用戶切換到NewsListFragment界面之後,界面需要展示新聞列表信息給用戶。首先NewsListFragment會調用NewsPresenter的loadNews方法,NewsPresenter 的loadNews方法中又會調用NewsModel中的loadNews方法。NewsModel中的loadNews方法中就是加載數據的核心,通過Okhttp請求服務器接口獲取數據,無論數據獲取成功與否,都會通過OnLoadNewsListener接口回調給NewsPresenter 。如果獲取成功,NewsPresenter 會調用NewsView的addNews方法將獲取的新聞列表信息展示到RecyclerView。如果獲取失敗,則調用NewsView的showLoadFialMsg方法向用戶提示失敗信息。

  以上就是新聞列表請求的整個過程。

  源碼地址:https://github.com/liuling07/SimpleNews

  轉載請注明出處:http://www.liuling123.com/2015/12/mvp-pattern-android.html

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved