T-Mvp搭建

1.添加依赖

implementation 'com.squareup.okhttp3:okhttp:3.8.1'

  implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'

implementation 'io.reactivex:rxjava:1.1.6'

// Retrofit的rx解析库

implementation 'com.squareup.retrofit2:retrofit:2.1.0'

implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

// Retrofit的gson库字符串库

implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

implementation 'com.orhanobut:logger:1.8'

//解决Android3.0以后不能butterknife问题

implementation 'com.jakewharton:butterknife:8.4.0'

annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

implementation 'io.reactivex:rxandroid:1.2.1'

2.copy Tutils工具类

public class Ttil {

public static   T getT(Object o, int i) {

try {

return ((Class) ((ParameterizedType) (o.getClass()

.getGenericSuperclass())).getActualTypeArguments()[i])

.newInstance();

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStac kTrace();

} catch (ClassCastException e) {

e.printStackTrace();

}

return null;

}

public static Class forName(String className) {

try {

return Class.forName(className);

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

return null;

}

}

3创建retrofit对象 RetrofitManager

public class RetrofitManager {

//地址

private String BaseURL = Contents.BASEURL;

private static OkHttpClient mOkHttpClient;

private Retrofit mRetrofit;

/**

* 构建Retrofit

*

* @return

*/

public Retrofit build() {

initOkHttpClient();

initRetrofit();

return mRetrofit;

}

public RetrofitManager() {

}

protected void initRetrofit() {

mRetrofit = new Retrofit.Builder()

.baseUrl(BaseURL)

.client(mOkHttpClient)

.addCallAdapterFactory(RxJavaCallAdapterFactory.create())

.addConverterFactory(GsonConverterFactory.create(new Gson()))

.build();

}

private void initOkHttpClient() {

//拦截器,用于输出网络请求和结果的 Log

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();

interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

//初始化OkHttpClient

mOkHttpClient = new OkHttpClient.Builder()

.addInterceptor(interceptor)

.retryOnConnectionFailure(true)

.connectTimeout(15, TimeUnit.SECONDS)

.build();

}

}

4.Contents 网址(也就是3baseurl)

public class Contents {

public static String BASEURL ="https://api.yunxuekeji.cn/";

}

5.LoginService接口

public interface LoginService {

@FormUrlEncoded

@POST("api/account/login")

rx.Observablelogin(@Field("phone") String

phone, @Field("password") String psw);

@GET("yunxue_app_api/diction/getdictionaryswithpid/KECHENGFENLEI")

rx.Observablelogin();

}

6.新建LoginContract(契约类,以Contract结尾),有了契约类后自动生成相关的base类

public class LoginContract {

public  interface View extends BaseView {

void succ(Bean bean);

}

public  interface Model extends BaseModel {

rx.Observable login ();

}

public  abstract static class Presenter extends BasePresenter {

abstract void login(String phone,String psw);

}

}

7.BaseModel初始化retrofit对象(BaseView不用搭理)

public interface BaseModel {

public RetrofitManager mretrofit=new RetrofitManager();

}

8.BasePresenter初始化presenter对象

public class LoginModel implements LoginContract.Model{

private LoginService loginService;

public LoginModel() {

loginService = mretrofit.build().create(LoginService.class);

}

public rx.Observable login() {

return loginService.login();2

}

}

9.在LoginContract自动生成的LoginModel中实现未实现的方法

public class LoginModel implements LoginContract.Model{

private LoginService loginService;

public LoginModel() {

loginService = mretrofit.build().create(LoginService.class);

}

public rx.Observable login() {

return loginService.login();2

}

}

10.在LoginContract自动生成的LoginPresenter中实现未实现的方法

public class LoginPresenter extends LoginContract.Presenter{

public void login(String phone, String psw) {

mModel.login()

.subscribeOn(Schedulers.io())

.observeOn(AndroidSchedulers.mainThread())

.subscribe(new Action1() {

@Override

public void call(Bean bean) {

mView.succ(bean);

}

}, new Action1() {

@Override

public void call(Throwable throwable) {

//  mView.succ(throwable.getMessage());

}

});

}

}

11.新建App(在baseactivity中一定要使用)

public class App extends Application {

public static AppCompatActivity mActivity;

public static Fragment mLastFragment;

private static Context context;

@Override

public void onCreate() {

super.onCreate();

context = getApplicationContext();

}

public static Context getContext() {

return context;

}

}

12.新建BaseActivity

public abstract class BaseActivity extends AppCompatActivity implements BaseView {

public T mPresenter;

public E mModel;

private FragmentManager manager;

private FragmentTransaction transaction;

private Fragment fragment;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

App.mActivity=this;

init();

}

protected void init() {

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

setContentView(getLayoutResID());

mPresenter = TUtil.getT(this, 0);

mModel = TUtil.getT(this, 1);

if (this instanceof BaseView) mPresenter.setMV(mModel,this );

initFragmentManager();

initView();

}

private void initFragmentManager() {

manager = App.mActivity.getSupportFragmentManager();

transaction = manager.beginTransaction();

}

public Fragment add(int containerId, Class fragmentClass, boolean isChild, Map map){

//用Fragment的名字设置一个tag值

String tag = fragmentClass.getSimpleName();

//使用tag值来判断当前Fragment是否实例化

fragment = manager.findFragmentByTag(tag);

//

if (fragment == null){

try {

//使用单例创建Fragment对象

fragment = fragmentClass.newInstance();

//使用add方法添加到容器中

transaction.add(containerId, fragment,tag);

//调用添加回退栈方法进行栈管理

//addToBackStack():  添加回退栈

transaction.addToBackStack(tag);

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

}

}

if (!isChild ) {

if (App.mLastFragment != null){

transaction.hide(App.mLastFragment);

}

}

if (map!=null) {

Bundle bundle=new Bundle();

for (Map.Entry entry : map.entrySet()) {

bundle.putString(entry.getKey(),entry.getValue());

}

}

transaction.show(fragment);

App.mLastFragment=fragment;

transaction.commit();

return fragment;

}

/**

* 获得Layout文件id

* @return

*/

protected abstract int getLayoutResID();

protected abstract void initView();

}

13.新建BaseFragment

public abstract class BaseFragment

BaseModel> extends Fragment {

public P p;

public M m;

@Nullable

@Override

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable

ViewGroup container, @Nullable Bundle savedInstanceState) {

View inflate = inflater.inflate(getLayoutId(), container, false);

p = TUtil.getT(this, 0);

m = TUtil.getT(this, 1);

if (this instanceof BaseView) {

p.setMV(m, this);

}

initView(inflate);

initData();

return inflate;

}

protected abstract void initView(View inflate);

protected abstract void initData();

protected abstract int getLayoutId();

}

14.在需要的地方继承BaseActivity/BaseFragment

你可能感兴趣的:(T-Mvp搭建)