MVP框架+Dagger2实现简单注册

 
  
 
  

工程里加入config.gradle

ext {
    android = [
            compileSdkVersion: 27,
            applicationId    : "com.bwei.mvp1",
            minSdkVersion    : 15,
            targetSdkVersion : 27,
            versionCode      : 1,
            versionName      : "1.0"
    ]

    dependencies = [
            "appcompat-v7"     : "com.android.support:appcompat-v7:27.1.1",
            "constraint-layout": "com.android.support.constraint:constraint-layout:1.1.0",
            "retrofit2"        : "com.squareup.retrofit2:retrofit:2.4.0",
            "converter-gson"   : "com.squareup.retrofit2:converter-gson:2.4.0",
            "adapter-rxjava"  :  "com.squareup.retrofit2:adapter-rxjava2:2.4.0",
            "rxjava2"          : "io.reactivex.rxjava2:rxjava:2.1.13",
            "rxjava2:rxandroid": "io.reactivex.rxjava2:rxandroid:2.0.2",
            "dagger"           : "com.google.dagger:dagger:2.8",
            "dagger-compiler" : "com.google.dagger:dagger-compiler:2.7"

    ]
}
工程的build.gradle最上面加入  apply from: "config.gradle"

    appbuild.gradle加入依赖,下面的从头到尾复制进去

apply plugin: 'com.android.application'

android {
    compileSdkVersion rootProject.ext.android.compileSdkVersion
    defaultConfig {
        applicationId rootProject.ext.android.applicationId
        minSdkVersion rootProject.ext.android.minSdkVersion
        targetSdkVersion rootProject.ext.android.targetSdkVersion
        versionCode rootProject.ext.android.versionCode
        versionName rootProject.ext.android.versionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation rootProject.ext.dependencies["appcompat-v7"]
    implementation rootProject.ext.dependencies["constraint-layout"]
    implementation rootProject.ext.dependencies["retrofit2"]
    implementation rootProject.ext.dependencies["converter-gson"]
    implementation rootProject.ext.dependencies["rxjava2"]
    implementation rootProject.ext.dependencies["rxjava2:rxandroid"]
    implementation rootProject.ext.dependencies["dagger"]
    annotationProcessor rootProject.ext.dependencies["dagger-compiler"]
    implementation rootProject.ext.dependencies["adapter-rxjava"]
    
    implementation 'com.android.support:support-v4:27.1.1'
}

activity_register.XML

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

    <EditText
        android:id="@+id/etMobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/bt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="注册"/>
LinearLayout>

bean类

import java.io.Serializable;

public class RegisterBean implements Serializable {

    /**
     * msg : 注册成功
     * code : 0
     */

    private String msg;
    private String code;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}

api包

import com.bwei.mvp1.bean.RegisterBean;

import io.reactivex.Observable;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface RegisterApiService {
    @FormUrlEncoded
    @POST("user/reg")
    Observable register(@Field("moble") String mobile,@Field("password")String password);
}
---------------

public class RegisterApi {
    private static RegisterApi registerApi;
    private RegisterApiService registerApiService;

    private RegisterApi(RegisterApiService registerApiService) {
        this.registerApiService = registerApiService;
    }

    public static RegisterApi getRegisterApi(RegisterApiService registerApiService) {
        if (registerApi == null) {
            registerApi = new RegisterApi(registerApiService);
        }
        return registerApi;
    }

    public Observable register(String mobile, String password) {
        return registerApiService.register(mobile, password);
    }
}

inter包
package com.bwei.mvp1.inter;

public interface IBase {
    int getContentLayout();
    void inject();
}

ui.base包
 
  
package com.bwei.mvp1.ui.base;

public interface BaseContract {
    interface BasePresenter<T extends BaseView> {
        void attachView(T view);

        void detachView();
    }


    interface BaseView {
        void showLoading();

        void dimissLoading();
    }
}
------------------------------
 
  
package com.bwei.mvp1.ui.base;

public class BasePresenter<T extends BaseContract.BaseView> implements BaseContract.BasePresenter<T>{
    protected T mView;

    @Override
    public void attachView(T view) {
        this.mView=view;
    }

    @Override
    public void detachView() {
        if(mView!=null){
            mView=null;
        }
    }
}
----------------------------
 
  
package com.bwei.mvp1.ui.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.bwei.mvp1.inter.IBase;

import javax.inject.Inject;

public abstract class BaseActivity<T extends BaseContract.BasePresenter> extends AppCompatActivity implements IBase,
        BaseContract.BaseView {
    @Inject
    protected T mPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentLayout());
        inject();
        mPresenter.attachView(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void dimissLoading() {

    }
}

component包

import com.bwei.mvp1.model.HttpModel;
import com.bwei.mvp1.ui.register.RegisterActivity;

import dagger.Component;

@Component(modules = HttpModel.class)
public interface HttpComponent {
    void injects(RegisterActivity registerActivity);
}

model包

import com.bwei.mvp1.api.RegisterApi;
import com.bwei.mvp1.api.RegisterApiService;

import java.util.concurrent.TimeUnit;

import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

@Module
public class HttpModel {

    @Provides
    OkHttpClient.Builder provideOkHttpClientBuilder() {
        return new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS);
    }

    @Provides
    RegisterApi provideRegisterApi(OkHttpClient.Builder builder) {
        RegisterApiService registerApiService = new Retrofit.Builder()
                .baseUrl("https://www.zhaoapi.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build()
                .create(RegisterApiService.class);

        return RegisterApi.getRegisterApi(registerApiService);
    }

}
 
  
ui.register.contract包

package com.bwei.mvp1.ui.register.contract;

import com.bwei.mvp1.ui.base.BaseContract;

public interface RegisterContract {
    interface View extends BaseContract.BaseView {
        void registerSuccess();
    }

    interface Presenter extends BaseContract.BasePresenter {
        void register(String mobile, String password);
    }
}

------------------------------------------

ui.register.presenter包

package com.bwei.mvp1.ui.register.presenter;

import com.bwei.mvp1.api.RegisterApi;
import com.bwei.mvp1.bean.RegisterBean;
import com.bwei.mvp1.ui.base.BasePresenter;
import com.bwei.mvp1.ui.register.contract.RegisterContract;

import javax.inject.Inject;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class RegisterPresenter extends BasePresenter implements RegisterContract.Presenter {
    RegisterApi registerApi;
    @Inject
    public RegisterPresenter(RegisterApi registerApi) {
        this.registerApi = registerApi;
    }

    @Override
    public void register(String mobile, String password) {
        registerApi.register(mobile, password)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(RegisterBean registerBean) {
                        mView.registerSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}

ui.register
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.bwei.mvp1.R;
import com.bwei.mvp1.component.DaggerHttpComponent;
import com.bwei.mvp1.model.HttpModel;
import com.bwei.mvp1.ui.base.BaseActivity;
import com.bwei.mvp1.ui.register.contract.RegisterContract;
import com.bwei.mvp1.ui.register.presenter.RegisterPresenter;

public class RegisterActivity extends BaseActivity implements RegisterContract.View, View .OnClickListener {

    private EditText mEtMobile;
    private EditText mEtPassword;
    /**
     * 注册
     */
    private Button mBt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_register;
    }

    @Override
    public void inject() {
        DaggerHttpComponent.builder()
                .httpModel(new HttpModel())
                .build()
                .injects(this);
    }

    @Override
    public void registerSuccess() {
        Toast.makeText(RegisterActivity.this, "注册成功了", Toast.LENGTH_SHORT).show();
    }

    private void initView() {
        mEtMobile = (EditText) findViewById(R.id.etMobile);
        mEtPassword = (EditText) findViewById(R.id.etPassword);
        mBt = (Button) findViewById(R.id.bt);
        mBt.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.bt:
                String mobile = mEtMobile.getText().toString();
                String password = mEtPassword.getText().toString();
                mPresenter.register(mobile, password);
                break;
        }
    }
}

你可能感兴趣的:(MVP框架+Dagger2实现简单注册)