用了這麼久的MVP,今天也在此記錄一下,好好學習,天天向上!!!感覺也沒啥說的,看代碼吧......
1、添加依賴
/*網絡請求*/
compile 'com.squareup.okio:okio:1.8.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'io.reactivex:rxandroid:1.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
2、Retrofit網絡框架封裝,支持RxJava
public class RetrofitUtils {
private Retrofit retrofit;
private RetrofitApiService retrofitApiService;
public RetrofitUtils() {
// 日誌攔截器
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
try {
String text = URLDecoder.decode(message, "utf-8");
LogT.i("OKHttp-----", text);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
LogT.i("OKHttp-----", message);
}
}
});
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
File cacheFile = new File(MaterialApplication.context.getCacheDir(), "cache");
Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
//設置超時時間、攔截、緩存(no)
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.cache(cache)
.build();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(RetrofitApiService.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())//支持RxJava
.build();
}
retrofitApiService = retrofit.create(RetrofitApiService.class);
}
// 創建單例
private static class SingletonHolder {
private static final RetrofitUtils INSTANCE = new RetrofitUtils();
}
public static RetrofitApiService getApiService() {
return SingletonHolder.INSTANCE.retrofitApiService;
}
}
----------------------------------------------------------------------------
public interface RetrofitApiService {
public static final String BASE_URL = "https://api.douban.com/v2/";//網絡請求地址
@GET("book/search")
Observable<BookBean> getSearchBook(@Query("q") String name, @Query("tag") String tag, @Query("start") int start, @Query("count") int count);
}
-----------------------------------------------------------------------------
再來一個管理類,管理我們的網絡請求:
public class DataManager {
private static final DataManager ourInstance = new DataManager();
private RetrofitApiService mRetrofitApiService;
public static DataManager getInstance() {
return ourInstance;
}
private DataManager() {
this.mRetrofitApiService = RetrofitUtils.getApiService();
}
public Observable<BookBean> getSearchBooks(String name, String tag, int start, int count){
return mRetrofitApiService.getSearchBook(name,tag,start,count);
}
}
3、MVP相關操作
a、抽取BasePresenter:
public class BasePresenter<V> {
public BaseActivty mContext;
public BasePresenter(BaseActivty context) {
mContext = context;
}
protected Reference<V> mViewRef;
public void attachView(V view) {
mViewRef = new WeakReference<V>(view);
}
public void detachView() {
if (mViewRef != null) {
mViewRef.clear();
mViewRef = null;
}
}
public V getView() {
return mViewRef != null ? mViewRef.get() : null;
}
}
b、抽取BaseActivity,BaseFragment做同樣的操作在onCreate方法中判斷是否使用MVP模式:
public abstract class BaseActivty<V, T extends BasePresenter<V>> extends AppCompatActivity {
protected T mPresenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//判斷是否使用MVP模式
mPresenter = createPresenter();
if (mPresenter != null) {
mPresenter.attachView((V) this);//因爲之後所有的子類都要實現對應的View接口
}
}
//用於創建Presenter和判斷是否使用MVP模式(由子類實現)
protected abstract T createPresenter();
@Override
protected void onDestroy() {
super.onDestroy();
if (mPresenter != null) {
mPresenter.detachView();
}
}
}
-----------------------------------------------------------------------------------------------
public abstract class BaseFragment<V, T extends BasePresenter<V>> extends Fragment {
protected T mPresenter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//判斷是否使用MVP模式
mPresenter = createPresenter();
if (mPresenter != null) {
mPresenter.attachView((V) this);//因爲之後所有的子類都要實現對應的View接口
}
}
//用於創建Presenter和判斷是否使用MVP模式(由子類實現)
protected abstract T createPresenter();
@Override
public void onDestroy() {
super.onDestroy();
if (mPresenter != null) {
mPresenter.detachView();
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = LayoutInflater.from(container.getContext()).inflate(getLayoutId(), container, false);
initView(view, savedInstanceState);
return view;
}
protected abstract boolean isStatusHave();
//獲取佈局文件ID
protected abstract int getLayoutId();
protected abstract void initView(View view, Bundle savedInstanceState);
}
4、處理具體業務
基本工作已經做完,現在可以開心的進行網絡請求,展示數據了。
public class BookFragment extends BaseFragment<BookView, BookPresenter> implements BookView {
@Bind(R.id.tv_name)
TextView mTvName;
@Override
protected BookPresenter createPresenter() {
return new BookPresenter((BaseActivty) getActivity());
}
@Override
protected boolean isStatusHave() {
return true;
}
@Override
protected int getLayoutId() {
return R.layout.fragment_book;
}
@Override
protected void initView(View view, Bundle savedInstanceState) {
ButterKnife.bind(this, view);
mPresenter.getBook("西遊記", null, 0, 1);
}
@Override
public void onGetBook(BookBean mBook) {
mTvName.setText(mBook.getBooks().get(0).getAuthor().get(0));
}
@Override
public void onError(String error) {
// TODO: 2017/12/7
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:gravity="center"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
-------------------------------------------------------------
BookPresenter 和 BookView :
public class BookPresenter extends BasePresenter<BookView> {
private BookBean mBook;
public BookPresenter(BaseActivty context) {
super(context);
}
public void getBook(String name, String tag, int start, int count) {
Observable<BookBean> searchBook = DataManager.getInstance().getSearchBooks(name, tag, start, count);
searchBook.subscribeOn(Schedulers.io())//請求數據的事件發生在io線程
.observeOn(AndroidSchedulers.mainThread())//請求完成後在主線程更顯UI
.subscribe(new Observer<BookBean>() {
@Override
public void onCompleted() {
getView().onGetBook(mBook);
}
@Override
public void onError(Throwable e) {
getView().onError(e.toString());
}
@Override
public void onNext(BookBean bookBean) {
mBook = bookBean;
}
});
}
}
public interface BookView {
void onGetBook(BookBean mBook);
void onError(String error);
}