-
前言
-
实践
- 前言
MVP(Model View Presenter)模式是MVC模式的一个演化版本,目前在Android应用开发中越来越重要。随着UI创建技术的功能日益增强,UI层也履行越来越多的职责。为了更好地细分视图(View)和模型(Model)的功能,让View专注于处理数据的可视化以及与用户的交互,同时让Model只关系数据的处理,基于MVC概念的MVP模式应运而生。
那什么是MVP模式呢?
MVP模式通常包含4个要素:
1.View:负责绘制UI元素,与用户进行交互(Android中体现为Activity/Fragment等)
2.View Interface:需要View实现的接口,View通过View Interface与Presenter进行交互,降低耦合,方便单元测试
3.Model:负责存储、检索、操作数据(有时实现一个Model Interface降低耦合)
4.Presenter:作为View与Model交互的中间纽带,处理与用户交互的逻辑
那么为什么在移动开发中推荐使用MVP呢?与MVC的差异在哪?
MVP是从MVC演变而来,它们的基本思想有想通的地方:Controller/Presenter负责逻辑的处理,Model提供数据,View负责显示。重大区别是在MVP中View并不直接使用Model,它们的通信是通过Presenter(MVC中的Controller)来进行的,所有的交互都发生在Presenter内部,而在MVC中View会直接从Model中读取数据。
我们在学习阶段写的逻辑一般都是在Activity中完成的,这样随着项目需求越来越多,Activity中代码越来越复杂,重构难度不断加大。同时也给测试提供了方便。
//新闻实体类
package com.lauren.simplenews.beans;
import java.io.Serializable;
public class NewsBean implements Serializable {
/** * docid */
private String docid;
/** * 标题 */
private String title;
/** * 小内容 */
private String digest;
/** * 图片地址 */
private String imgsrc;
/** * 来源 */
private String source;
/** * 时间 */
private String ptime;
/** * TAG */
private String tag;
public String getDocid() { return docid; }
public void setDocid(String docid) { this.docid = docid; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getDigest() { return digest; }
public void setDigest(String digest) { this.digest = digest; }
public String getImgsrc() { return imgsrc; }
public void setImgsrc(String imgsrc) { this.imgsrc = imgsrc; }
public String getSource() { return source; }
public void setSource(String source) { this.source = source; }
public String getPtime() { return ptime; }
public void setPtime(String ptime) { this.ptime = ptime; }
public String getTag() { return tag; }
public void setTag(String tag) { this.tag = tag; }
}
//Model Interface
public interface NewsModel {
void loadNews(String url, int type, NewsModelImpl.OnLoadNewsListListener listener);
void loadNewsDetail(String docid, NewsModelImpl.OnLoadNewsDetailListener listener);
}
//Model Impl
public class NewsModelImpl implements NewsModel {
@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);
}
@Override
public void loadNewsDetail(final String docid, final OnLoadNewsDetailListener listener) {
String url = getDetailUrl(docid);
OkHttpUtils.ResultCallback<String> loadNewsCallback = new OkHttpUtils.ResultCallback<String>() {
@Override
public void onSuccess(String response) {
NewsDetailBean newsDetailBean = NewsJsonUtils.readJsonNewsDetailBeans(response, docid);
listener.onSuccess(newsDetailBean);
}
@Override
public void onFailure(Exception e) {
listener.onFailure("load news detail info failure.", e);
}
};
OkHttpUtils.get(url, loadNewsCallback);
}
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);
}
public interface OnLoadNewsDetailListener {
void onSuccess(NewsDetailBean newsDetailBean);
void onFailure(String msg, Exception e);
}
}
//View Interface
public interface NewsView {
void showProgress();
void addNews(List<NewsBean> newsList);
void hideProgress();
void showLoadFailMsg();
}
//View
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.addOnScrollListener(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();
}
View view = getActivity() == null ? mRecyclerView.getRootView() :
getActivity().findViewById(R.id.drawer_layout);
Snackbar.make(view, getString(R.string.load_fail), Snackbar.LENGTH_SHORT).show();
}
@Override
public void onRefresh() {
pageIndex = 0;
if(mData != null) {
mData.clear();
}
mNewsPresenter.loadNews(mType, pageIndex);
}
}