- @return fragment
*/
public Fragment getFragment() {
return this;
}
}`
2.1.5 BasePresenter
`/**
- created by xucanyou666
- on 2020/1/16 17:12
- email:913710642@qq.com
/
public abstract class BasePresenter {
//将所有正在处理的Subscription都添加到CompositeSubscription中。统一退出的时候注销观察
private CompositeDisposable mCompositeDisposable;
private V baseView;
/* - 和View绑定
- @param baseView
/
public void attachView(V baseView) {
this.baseView = baseView;
}
/* - 解绑View,该方法在BaseMvpActivity类中被调用
/
public void detachView() {
baseView = null;
// 在界面退出等需要解绑观察者的情况下调用此方法统一解绑,防止Rx造成的内存泄漏
if (mCompositeDisposable != null) {
mCompositeDisposable.dispose();
}
}
/* - 获取View
- @return view
/
public V getMvpView() {
return baseView;
}
/* - 将Disposable添加,在每次网络访问之前初始化时进行添加操作
- @param subscription subscription
*/
public void addDisposable(Disposable subscription) {
//csb 如果解绑了的话添加 sb 需要新的实例否则绑定时无效的
if (mCompositeDisposable == null || mCompositeDisposable.isDisposed()) {
mCompositeDisposable = new CompositeDisposable();
}
mCompositeDisposable.add(subscription);
}
}`
2.1.6 MyApplication
`package com.users.xucanyou666.rxjava2_retrofit_mvp.base;
import android.app.Application;
import android.content.Context;
/**
- 基类
- created by xucanyou666
- on 2019/11/2 14:46
- email:913710642@qq.com
- @author xucanyou666
*/
public class MyApplication extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
public static Context getContext() {
return context;
}
}`
2.2 工具类 Util
2.2.1 RetrofitManager
`/**
- Retrofit单例工具类
- created by xucanyou666
- on 2020/1/16 16:38
- email:913710642@qq.com
/
public class RetrofitManager {
private Retrofit mRetrofit;
//构造器私有,这个工具类只有一个实例
private RetrofitManager() {
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
httpClientBuilder.connectTimeout(15, TimeUnit.SECONDS);
mRetrofit = new Retrofit.Builder()
.client(httpClientBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL)
.build();
}
/* - 静态内部类单例模式
- @return
/
public static RetrofitManager getInstance() {
return Inner.retrofitManager;
}
private static class Inner {
private static final RetrofitManager retrofitManager = new RetrofitManager();
}
/* - 利用泛型传入接口class返回接口实例
- @param ser 类
- @param 类的类型
- @return Observable
*/
public T createRs(Class ser) {
return mRetrofit.create(ser);
}
}`
2.2.2 RxJavaUtil
`/**
- created by xucanyou666
- on 2019/11/17 19:20
- email:913710642@qq.com
- @author xucanyou666
/
public class RxJavaUtil {
/* - 线程调度工作
- @param observable 被观察者
- @param 类型
*/
public static Observable toSubscribe(Observable observable) {
return observable.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
}`
2.3 常量类 Contant
`/**
- created by xucanyou666
- on 2019/11/17 19:01
- email:913710642@qq.com
*/
public class StaticQuality {
public static final String BASE_URL=“https://api.gushi.ci/”;
}`
2.4 接口管理器 Contract
`/**
- 诗歌的接口管理器
- created by xucanyou666
- on 2020/2/2 15:33
- email:913710642@qq.com
/
public interface IPoetryContract {
interface IPoetryModel {
/* - 得到诗歌
- @return 诗歌
/
Observable getPoetry();
}
interface IPoetryPresenter {
void getPoetry();
}
interface IPoetryView extends BaseView {
/* - @param author 作者
*/
void searchSuccess(String author);
}
}`
2.5 实体类 Entity
`/**
- 诗歌的实体类
- created by xucanyou666
- on 2020/1/23 21:23
- email:913710642@qq.com
- API返回示例:
- {
- “content”: “胡瓶落膊紫薄汗,碎叶城西秋月团。”,
- “origin”: “从军行七首”,
- “author”: “王昌龄”,
- “category”: “古诗文-天气-月亮”
- }
*/
public class PoetryEntity {
private String content; //诗歌内容
private String origin; //来源
private String author; //作者
private String category; //分类
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}`
2.6 Retrofit
接口 iApiService
`/**
- retrofit接口
- created by xucanyou666
- on 2020/1/23 21:25
- email:913710642@qq.com
/
public interface GetPoetryEntity {
/* - 获取古诗词
- @return 古诗词
*/
@GET(“all.json”)
Observable getPoetry();
}`
2.7 视图层 View
2.7.1 MainActivity
`/**
- Description : MainActivity
- @author XuCanyou666
- @date 2020/2/3
*/
public class MainActivity extends BaseMvpActivity<MainActivit 《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》无偿开源 徽信搜索公众号【编程进阶路】 y, PoetryPresenter> implements IPoetryContract.IPoetryView {
@BindView(R.id.btn_get_poetry)
Button btnGetPoetry;
@BindView(R.id.tv_poetry_author)
TextView tvPoetryAuthor;
@BindView(R.id.btn_goto_fragment)
Button btnGotoFragment;
@BindView(R.id.ll)
LinearLayout ll;
@Override
protected void initViews() {
}
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected PoetryPresenter createPresenter() {
return PoetryPresenter.getInstance();
}
@Override
public void searchSuccess(String author) {
tvPoetryAuthor.setText(author);
}
@Override
public void showProgressDialog() {
}
@Override
public void hideProgressDialog() {
}
@Override
public void onError(String result) {
Toast.makeText(MyApplication.getContext(), result, Toast.LENGTH_SHORT).show();
}
@OnClick({R.id.btn_get_poetry, R.id.btn_goto_fragment})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.btn_get_poetry:
getPresenter().getPoetry();
break;
case R.id.btn_goto_fragment:
startFragment(R.id.ll, new MainFragment());
break;
default:
break;
}
}
}`
2.7.2 MainFragment
`/**
- Description : MainFragment
- @author XuCanyou666
- @date 2020/2/2
*/
public class MainFragment extends BaseFragment implements IPoetryContract.IPoetryView {
@BindView(R.id.btn_get_poetry)
Button btnGetPoetry;
@BindView(R.id.tv_poetry_author)
TextView tvPoetryAuthor;
@Override
public View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public PoetryPresenter initPresenter() {
return PoetryPresenter.getInstance();
}
@Override
public void showProgressDialog() {
}
@Override
public void hideProgressDialog() {
}
@Override
public void onError(String result) {
Toast.makeText(MyApplication.getContext(), result, Toast.LENGTH_SHORT).show();
}
@OnClick(R.id.btn_get_poetry)
public void onViewClicked() {
getPresenter().getPoetry();
}
@Override
public void searchSuccess(String author) {
tvPoetryAuthor.setText(author);
}
}`
2.8 Presenter
层
`/**
- created by xucanyou666
- on 2020/1/16 17:09
- email:913710642@qq.com
/
public class PoetryPresenter extends BasePresenter<IPoetryContract.IPoetryView> implements IPoetryContract.IPoetryPresenter {
private static final String TAG = “PoetryPresenter”;
private PoetryEntity mPoetryEntity;
private PoetryModel mPoetryModel;
private PoetryPresenter() {
mPoetryModel = PoetryModel.getInstance();
}
public static PoetryPresenter getInstance() {
return Inner.instance;
}
private static class Inner {
private static final PoetryPresenter instance = new PoetryPresenter();
}
/* - 得到诗歌
*/
@Override
public void getPoetry() {
Observable observable = mPoetryModel.getPoetry().doOnSubscribe(new Consumer() {
@Override
public void accept(Disposable disposable) throws Exception {
addDisposable(disposable);
}
});
observable = RxJavaUtil.toSubscribe(observable);
observable.subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(PoetryEntity poetryEntity) {
mPoetryEntity = poetryEntity;
}
@Override
public void onError(Throwable e) {
getMvpView().onError(e.getMessage());
Log.d(TAG, "onError: " + e.getMessage());
}
@Override
public void onComplete() {
if (mPoetryEntity != null) {
getMvpView().searchSuccess(mPoetryEntity.getAuthor());
}
}
});
}
}`
2.9 Model
层
`/**
- created by xucanyou666
- on 2020/1/16 17:06
- email:913710642@qq.com
/
public class PoetryModel implements IPoetryContract.IPoetryModel {
private PoetryModel() {
}
public static PoetryModel getInstance() {
return Inner.instance;
}
private static class Inner {
private static final PoetryModel instance = new PoetryModel();
}
/* - 获取古诗词
- @return 古诗词
*/
@Override
public Observable getPoetry() {
return RetrofitManager.getInstance().createRs(GetPoetryEntity.class).getPoetry();
}
}`
2.10 app.build.gradle
apply plugin: 'com.android.application' android { compileSdkVersion 28 compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "com.users.xucanyou666.rxjava2_retrofit_mvp" minSdkVersion 19 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { // RxJava implementation 'io.reactivex.rxjava2:rxjava:2.1.12' implementation 'com.squareup.retrofit2:retrofit:2.6.0' // Retrofit和jxjava关联 implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0' // Retrofit使用Gson转换 implementation 'com.squareup.retrofit2:converter-gson:2.4.0' // RxAndroid implementation 'io.reactivex.rxjava2:rxandroid:2.0.2' //引入ButterKnife implementation "com.jakewharton:butterknife:10.2.0" implementation 'androidx.legacy:legacy-support-v4:1.0.0' annotationProcessor "com.jakewharton:butterknife-compiler:10.2.0" implementation "com.google.android.material:material:1.0.0" implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' }
三.我在使用中遇到的问题
3.1 网络权限忘记授予
- 解决措施:加上权限即可
<uses-permission android:name="android.permission.INTERNET" />
3.2 ButterKnife
框架版本问题
使用ButterKnife
框架的时候
当是androidX
的时候,需要implementation 10.2.0
版本的ButterKnife
//引入ButterKnife implementation "com.jakewharton:butterknife:10.2.0" implementation 'androidx.legacy:legacy-support-v4:1.0.0' annotationProcessor "com.jakewharton:butterknife-compiler:10.2.0"
当是android 28
等其他版本的时候,可以导入8.4.0
版本的ButterKnife
(导入10.2.0
版本会出错)
implementation 'com.jakewharton:butterknife:8.4.0' annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'