Android知识整理Android知识Android开发

使用Mobsy进行MVP实战

2016-10-26  本文已影响427人  黄怡菲

MVP介绍

如下为典型的MVP工作流程

mvp-workflow.png

需要注意的点:

  1. Presenter不应该直接处理View的事件
  2. View只应向Presenter传递消息,并接受Presenter的命令
  3. Activity和Fragment是View的一部分,一般可用于处理用户事件
  4. Presenter和Model应该是纯Java代码,而且可以独立的运行单元测试

Mosby介绍

gradle依赖

dependencies {
    //...
    
    compile 'com.hannesdorfmann.mosby:mvp:2.0.1'
    compile 'com.hannesdorfmann.mosby:viewstate:2.0.1'
    
    //...
}

MvpView和MvpPresenter

public interface MvpView { }


public interface MvpPresenter<V extends MvpView> {

  public void attachView(V view);

  public void detachView(boolean retainInstance);
}

通过MvpLceFragment学习使用MVP

LCE就是Loading-Content-Error,代表了一个典型的移动互联网应用的页面。

  1. 显示LoadingView,并在后台获取数据
  2. 如果获取成功,显示获取的到数据
  3. 如果失败,显示一个错误的提示View

先看看MvpLceView

/**
 * @param <M> The type of the data displayed in this view
 */
public interface MvpLceView<M> extends MvpView {

  /**
   * Display a loading view while loading data in background.
   * <b>The loading view must have the id = R.id.loadingView</b>
   *
   * @param pullToRefresh true, if pull-to-refresh has been invoked loading.
   */
  public void showLoading(boolean pullToRefresh);

  /**
   * Show the content view.
   *
   * <b>The content view must have the id = R.id.contentView</b>
   */
  public void showContent();

  /**
   * Show the error view.
   * <b>The error view must be a TextView with the id = R.id.errorView</b>
   *
   * @param e The Throwable that has caused this error
   * @param pullToRefresh true, if the exception was thrown during pull-to-refresh, otherwise
   * false.
   */
  public void showError(Throwable e, boolean pullToRefresh);

  /**
   * The data that should be displayed with {@link #showContent()}
   */
  public void setData(M data);
}

实现MvpLceView的控件或页面一定要包含至少3个View,他们的id分别为R.id.loadingView,R.id.contentViewR.id.errorView,因此我们使用如下的xml为Fragment布局。

库工程中的MvpLceFragmentMvpLceActivity已经实现了MvpLceView的三个方法
showLoadingshowContentshowError

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

  <!-- Loading View -->
  <ProgressBar
    android:id="@+id/loadingView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:indeterminate="true"
    />

  <!-- Content View -->
  <android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/contentView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

    </android.support.v4.widget.SwipeRefreshLayout>


    <!-- Error view -->
    <TextView
      android:id="@+id/errorView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      />

</FrameLayout>

这个页面中将显示一个从网络获取的国家列表,先看看Presenter的代码。这里通过CountriesAsyncLoader获取国家列表,并通过setData和showContent让View显示这些国家信息。当然还获取前显示Loading,获取失败后显示Error。

public class CountriesPresenter extends MvpBasePresenter<CountriesView> {

  @Override
  public void loadCountries(final boolean pullToRefresh) {

    getView().showLoading(pullToRefresh);


    CountriesAsyncLoader countriesLoader = new CountriesAsyncLoader(
        new CountriesAsyncLoader.CountriesLoaderListener() {

          @Override public void onSuccess(List<Country> countries) {

            if (isViewAttached()) {
              getView().setData(countries);
              getView().showContent();
            }
          }

          @Override public void onError(Exception e) {

            if (isViewAttached()) {
              getView().showError(e, pullToRefresh);
            }
          }
        });

    countriesLoader.execute();
  }
}

最后是MvpLceFragment,注意其中的createPresenter是所有的MvpView都需要实现的方法,用于创建和MvpView关联的Presenter,另一个setData两个方法是MvpLceFragment中没有实现的方法,因为只有实现的时候才知道最终的Model,已经如何显示这个Model。

另一个要注意的是MvpLceFragment的四个范型,依次是:显示内容的AndroidView,需要显示的内容Model,MvpView,MvpPresenter。

public class CountriesFragment
    extends MvpLceFragment<SwipeRefreshLayout, List<Country>, CountriesView, CountriesPresenter>
    implements CountriesView, SwipeRefreshLayout.OnRefreshListener {

  @Bind(R.id.recyclerView) RecyclerView recyclerView;
  CountriesAdapter adapter;

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.countries_list, container, false);
  }

  @Override public void onViewCreated(View view, @Nullable Bundle savedInstance) {
    super.onViewCreated(view, savedInstance);

    // Setup contentView == SwipeRefreshView
    contentView.setOnRefreshListener(this);

    // Setup recycler view
    adapter = new CountriesAdapter(getActivity());
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(adapter);
    loadData(false);
  }

  public void loadData(boolean pullToRefresh) {
    presenter.loadCountries(pullToRefresh);
  }

  @Override protected CountriesPresenter createPresenter() {
    return new SimpleCountriesPresenter();
  }

  @Override public void setData(List<Country> data) {
    adapter.setCountries(data);
    adapter.notifyDataSetChanged();
  }

  @Override public void onRefresh() {
    loadData(true);
  }
}

实战——封装一个LceListView

这部分代码可参考代码,只用关注mvplist包下的相关代码即可。

这个页面的View结构和之前的MvpLceFrgment类似,并通过修改Adapter给RecycleView的末尾增加了一个LoadMoreView。将这类业务的下拉刷新,上拉加载更多,以及错误处理都抽象出来。实现列表时,剩下的逻辑主要包括

  1. Model:获取的数据,以及从数据中获取每个列表项展示需要的数据列表
  2. Presenter:刷新和加载更多时,分别调用Model的获取数据方法
  3. View:根据数据决定ViewHolder的类型,以及ViewHolder的实现

如何使用,可以参考mvplist.sample包的内容

基类LecListView的方案

LecListView包含了一个LoadMoreView,LoadMoreView也符合Mvp架构。

我们先看看LoadMoreView的实现。

LoadMoreView

LecListView

```Java
public interface IListModel<M> {
    List<M> getData();
}
``` 

参考文章

上一篇 下一篇

猜你喜欢

热点阅读