MVC由Model、View、Control組成。
Model數據模型,提供數據
View視圖模型,提供視圖展現
Control控制器,負責控制Model和View通訊java
MVC在Android中的應用,以下圖,Activity爲Control,XML爲View,請求網絡數據模塊爲Model。View箭頭指向Control意爲傳遞數據,那就是Control獲取View的數據傳遞給Model來請求網絡,請求到的數據直接傳遞給View來顯示,這是一條主線。還有一條就是底部這兩個箭頭,也就是說Model能夠不經過Control,直接獲取View的數據,而後再返回結果數據給View。react
MVP由Model、View、Presenter組成。
Model數據模型,提供數據
View視圖模型,提供視圖展現
Presenter主持者,負責邏輯處理android
MVP與MVC最明顯的區別就在於Presenter和Control了。以下圖,Presenter傳遞數據給Model,Model獲得數據來請求網絡,再返回數據給Presenter,Presenter再把獲得的Model數據傳遞給View顯示。MVP總體的一個流程就是這樣。相比MVC來講,Model和View互相不干涉,達到徹底解耦緩存
估計上面文字性的解釋都聽得有點暈,那咱們就拿個例子來實戰一下吧網絡
下面和你們一塊兒完成一個簡單查詢快遞信息的例子,裏面用到了當下最流行的架構RxJava+Retrofit+MVP+OkHttp,很是值得你們一學架構
在builde.gradle裏面添加app
compile 'com.android.support:appcompat-v7:23.3.0' compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' compile 'com.squareup.okhttp3:okhttp:3.4.1' compile 'io.reactivex:rxandroid:1.2.1' compile 'io.reactivex:rxjava:1.1.6' compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
在AndroidManifest.xml添加所需權限異步
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
public class MainApp extends Application { @Override public void onCreate() { super.onCreate(); //初始化retrofitUtils RetrofitUtils.getInstance().initOkHttp(this); } }
在MainApp中初始化Retrofit,設置超時和baseUrl,添加了日誌攔截以及RxJava和數據解析,並暴露一個getRetrofit()方法供須要的地方調用ide
public class RetrofitUtils { private Retrofit retrofit; private String baseUrl = "http://www.kuaidi100.com/"; private static class SingleLoader{ private static final RetrofitUtils INSTANCE = new RetrofitUtils(); } public static RetrofitUtils getInstance(){ return SingleLoader.INSTANCE; } public void initOkHttp(@NonNull Context context){ HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10000L,TimeUnit.MILLISECONDS) //設置鏈接超時 .readTimeout(10000L,TimeUnit.MILLISECONDS) //設置讀取超時 .writeTimeout(10000L, TimeUnit.MILLISECONDS) //設置寫入超時 .cache(new Cache(context.getCacheDir(),10 * 1024 * 1024)) //設置緩存目錄和10M緩存 .addInterceptor(interceptor) //添加日誌攔截器(該方法也能夠設置公共參數,頭信息) .build(); retrofit = new Retrofit.Builder() .client(client) //設置OkHttp .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) // 添加數據解析ConverterFactory .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //添加RxJava .build(); } public Retrofit getRetrofit(){ return retrofit; } }
public interface PostSearchModel { /** * 請求快遞信息 * @param type 快遞類型 * @param postid 快遞單號 * @param callback 結果回調 */ void requestPostSearch(String type,String postid,PostSearchCallback callback); interface PostSearchCallback{ void requestPostSearchSuccess(PostQueryInfo postQueryInfo); void requestPostSearchFail(String failStr); } }
建立這個PostSearchModel接口,方便後期能夠不修改以前代碼靈活切換多種實現方式函數
public interface PostServiceBiz { @POST("query") Observable<PostQueryInfo> searchRx(@Query("type") String type, @Query("postid") String postid); }
public class PostQueryInfo { private String message; private String nu; private String ischeck; private String com; private String status; private String condition; private String state; private List<DataBean> data; public static class DataBean { private String time; private String context; private String ftime; } }
PostQueryInfo沒有添加get和set方法,你們自行快捷鍵了
PostSearchModelImpl實現上面PostSearchModel接口,利用上一篇文章裏學的Retrofit結合RxJava來請求網絡
這裏傳了PostSearchCallback回調函數,成功或者失敗都經過回調函數返回,徹底不須要考慮其它
public class PostSearchModelImpl implements PostSearchModel { @Override public void requestPostSearch(String type, String postid, final PostSearchCallback callback) { RetrofitUtils.getInstance() .getRetrofit() .create(PostServiceBiz.class) .searchRx(type,postid) //訪問網絡切換異步線程 .subscribeOn(Schedulers.io()) //響應結果處理切換成主線程 .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<PostQueryInfo>() { @Override public void onCompleted() { //請求結束回調 } @Override public void onError(Throwable e) { //錯誤回調 callback.requestPostSearchFail(e.getMessage()); } @Override public void onNext(PostQueryInfo postQueryInfo) { //成功結果返回 callback.requestPostSearchSuccess(postQueryInfo); } }); } }
activity_main.xml主界面佈局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".ui.MainActivity" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="快遞公司名:"/> <EditText android:id="@+id/post_name_et" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="yuantong"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="快 遞 單 號:" /> <EditText android:id="@+id/post_id_et" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="500379523313"/> </LinearLayout> <Button android:id="@+id/post_search_bn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查詢"/> <ListView android:id="@+id/post_list_lv" android:layout_width="match_parent" android:layout_height="match_parent" android:listSelector="@null" android:background="@null"/> </LinearLayout>
view_item_logistics.xml
listview適配器的item佈局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#FFFFFF" android:orientation="vertical" android:padding="15dp"> <TextView android:id="@+id/tv_conent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#8f8f8f" android:textSize="14sp" android:text="【深圳市】廣東分公司已出發" /> <TextView android:layout_marginTop="13dp" android:id="@+id/tv_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#8f8f8f" android:textSize="12sp" android:layout_marginBottom="13dp" android:paddingLeft="6dp" android:text="2016-05-03 18:23" /> </LinearLayout>
ListView適配器
public class LogisticsAdapter extends BaseAdapter { private List<PostQueryInfo.DataBean> datas; private LayoutInflater inflater; public LogisticsAdapter(Context context, List<PostQueryInfo.DataBean> datas) { this.datas = datas; inflater = LayoutInflater.from(context); } @Override public View getView(int i, View view, ViewGroup viewGroup) { PostQueryInfo.DataBean data = datas.get(i); view = inflater.inflate(R.layout.view_item_logistics, null); TextView tv_content= (TextView) view.findViewById(R.id.tv_conent); TextView tv_date= (TextView) view.findViewById(R.id.tv_date); tv_content.setText(data.getContext().replace("[","【").replace("]","】")); tv_date.setText(data.getTime()); return view; } @Override public int getCount() { return datas != null ? datas.size() : 0; } @Override public Object getItem(int i) { return datas.get(i); } @Override public long getItemId(int i) { return i; } }
BaseView提供通用顯示和隱藏加載框,若是有通用的方法均可以在寫在這裏面
public interface BaseView { void showProgressDialog(); void hideProgressDialog(); }
MainView接口繼承提供MainActivity全部須要更新界面UI的方法
public interface MainView extends BaseView{ void updateListUI(PostQueryInfo postQueryInfo); void errorToast(String message); }
BaseActivity實現BaseVew全部接口方法
public class BaseActivity extends Activity implements BaseView{ private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); progressDialog = new ProgressDialog(this); progressDialog.setMessage("查詢中..."); } @Override public void showProgressDialog(){ if(progressDialog!=null){ progressDialog.show(); } } @Override public void hideProgressDialog(){ if(progressDialog!=null&&progressDialog.isShowing()){ progressDialog.dismiss(); } } }
MainActivity繼承BaseActivity實現MainView全部方法供PostPresenter調用,點擊查詢按鈕經過實例化的PostPresenter,調用相關方法,後面的事情就所有交給PostPresenter去處理了,在activity銷燬的時候調用postPresenter.detach()防止內存泄漏
public class MainActivity extends BaseActivity implements View.OnClickListener, MainView { private EditText post_name_et; private EditText post_id_et; private ListView post_list_lv; private Button post_search_bn; private PostPresenter postPresenter; private List<PostQueryInfo.DataBean> dataArray = new ArrayList<>(); private LogisticsAdapter logisticsAdapter; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); initEvent(); } private void initView() { post_name_et = (EditText) findViewById(R.id.post_name_et); post_id_et = (EditText) findViewById(R.id.post_id_et); post_list_lv = (ListView) findViewById(R.id.post_list_lv); post_search_bn = (Button) findViewById(R.id.post_search_bn); } private void initData() { logisticsAdapter = new LogisticsAdapter(getApplicationContext(),dataArray); postPresenter = new PostPresenter(this); post_list_lv.setAdapter(logisticsAdapter); } private void initEvent() { post_search_bn.setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.post_search_bn: postPresenter.requestHomeData(post_name_et.getText().toString(),post_id_et.getText().toString()); break; } } @Override public void updateListUI(PostQueryInfo postQueryInfo) { dataArray.clear(); dataArray.addAll(postQueryInfo.getData()); logisticsAdapter.notifyDataSetChanged(); } @Override public void errorToast(String message) { Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show(); } @Override protected void onDestroy(){ //防止activity銷燬,postPresenter對象還存在形成的內存泄漏 if(postPresenter!=null) postPresenter.detach(); super.onDestroy(); } }
BasePresenter基類,提供了一個通用view對象,以及初始化和銷燬view對象的方法
public abstract class BasePresenter<T>{ public T mView; public void attach(T view){ this.mView = view; } public void detach(){ mView = null; } }
PostPresenter在構造函數中經過基類attach的方法初始化MainActivity提供的view對象,實例化PostSearchModelImpl對象,經過它提供的方法來請求網絡數據,在成功和失敗回調的函數裏,能夠作一些邏輯處理,經過view對象更新相應的UI
public class PostPresenter extends BasePresenter<MainView>{ private PostSearchModel postSearchModel; public PostPresenter(MainView mainView){ attach(mainView); postSearchModel = new PostSearchModelImpl(); } public void requestHomeData(String type,String postid){ if(postSearchModel == null||mView == null) return; mView.showProgressDialog(); postSearchModel.requestPostSearch(type, postid, new PostSearchModel.PostSearchCallback() { @Override public void requestPostSearchSuccess(PostQueryInfo postQueryInfo) { mView.hideProgressDialog(); if(postQueryInfo!=null&&"ok".equals(postQueryInfo.getMessage())) { mView.updateListUI(postQueryInfo); } } @Override public void requestPostSearchFail(String failStr) { mView.hideProgressDialog(); mView.errorToast(failStr); } }); } }
到這裏所有代碼基本都已編寫完,代碼的結構以下圖:
下面就運行程序看看效果吧,快遞公司名和快遞單號默認填寫上去了,你們只須要點擊查詢,結果和下面圖片同樣就說明成功了
爲何沒有直接提供一個能夠運行的DEMO出來,緣由很簡單就是但願你們可以跟着一步一步學習,而後動手慢慢邊敲代碼邊理解,最後敲完運行成功,應該就會更加理解MVP了。