Android MVP架构搭建

一、 MVP概念

M : Model (数据层) 用于加载数据,

V:View(视图层) 加载界面及视图

P:Presenter(交互层) 进行逻辑操作

二、MVP的优点

1.Model层与View层完全分离( 不用担心改需求了)

2.分工更加明确,逻辑更加清晰,易于维护代码

3.便于单元测试

其他……

三、实例(简单的登录)

1.新建项目,建立如下的包及项目结构:

2.Bean包中包含两个类,分别是User 和 LoginResult,代码如下:

public class LoginResult {
    public  boolean success;
    public  boolean nameErr;
    public  boolean passwordErr;
    public  String errMsg;

    public LoginResult(boolean success, boolean nameErr, boolean passwordErr, String errMsg) {
        this.success = success;
        this.nameErr = nameErr;
        this.passwordErr = passwordErr;
        this.errMsg = errMsg;
    }
} 
public class User {
    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public  String username;
    public  String password;
}

3.Model层中,建立IUserModel接口,UserModel继承该接口,并实现userLogin方法。

public interface IUserModel {
       void Login(User user , UserLoginCompleteListener listener);
       interface  UserLoginCompleteListener{
           void  onUserLoginCompleted(LoginResult result);
       }
}
import android.os.Handler;
import android.shinetech.com.finalmvpdemo.Bean.LoginResult;
import android.shinetech.com.finalmvpdemo.Bean.User;
import android.text.TextUtils;

public class UserModel  implements   IUserModel{
    @Override
    public void Login( final User user, final UserLoginCompleteListener listener) {
        Handler handler = new Handler() ;
        handler.post(new Runnable() {
            @Override
            public void run() {
                LoginResult result = new LoginResult(true, false ,false,"");
                if(TextUtils.isEmpty(user.username) ){
                    result.success = false;
                    result.nameErr = true;
                    result.errMsg = "Username is empty";
                }
                if(TextUtils.isEmpty(user.password) ){
                    result.success = false;
                    result.passwordErr = true;
                    result.errMsg = "Password is empty";
                }
                listener.onUserLoginCompleted(result);
            }
        });

    }
}

4.Presenter层建立抽象类BasePresenter,并实现UserLoginPresenter.其中BasePresenter可以是所有Presenter的父类,该类中用WeakReference(弱引用)来减少内存泄漏的风险。

import java.lang.ref.WeakReference;

public class BasePresenter<V> {
    WeakReference<V> weakReference;

    public  void detachView(){
        if(weakReference != null){
            weakReference.clear();
        }
    }

    public  void attachView(V view){
         weakReference = new  WeakReference<V>((V)view);
    }

    public V getView(){
        return  weakReference.get();
    } 
}

UserLoginPresenter类继承自BasePresenter,并实现了ILoginView的接口,该接口包含了界面显示的一些方法,如showProgressBar等。

import android.shinetech.com.finalmvpdemo.Bean.LoginResult;
import android.shinetech.com.finalmvpdemo.Bean.User;
import android.shinetech.com.finalmvpdemo.LoginActivity;
import android.shinetech.com.finalmvpdemo.Model.IUserModel;
import android.shinetech.com.finalmvpdemo.Model.UserModel;
import android.shinetech.com.finalmvpdemo.View.ILoginView;
import android.view.View;

public class UserLoginPresenter extends BasePresenter<LoginActivity> implements ILoginView {

    IUserModel model = new UserModel();

    public void login(User user) {
        showProgress(View.VISIBLE);
        model.Login(user, new IUserModel.UserLoginCompleteListener() {
            @Override
            public void onUserLoginCompleted(LoginResult result) {
                if (result.success) {
                    showSuccess();
                } else if (result.nameErr) {
                    showNameError();
                    showError(result.errMsg);
                } else if (result.passwordErr) {
                    showPasswordError();
                    showError(result.errMsg);
                }
                showProgress(View.INVISIBLE);
            }
        });
    }

    @Override
    public void showNameError() {
        getView().showNameError();
    }

    @Override
    public void showPasswordError() {
        getView().showPasswordError();
    }

    @Override
    public void showProgress(int visiblity) {
        getView().showProgress(visiblity);
    }

    @Override
    public void showSuccess() {
        getView().showSuccess();
    }

    @Override
    public void showError(String errMsg) {
        getView().showError(errMsg);
    }
}

5.在View层,建立了BaseActivity,所有的Activity都可以继承自此类,减少重复代码,并用泛型将presenter实例化推层到具体的界面层。

import android.os.Bundle;
import android.shinetech.com.finalmvpdemo.Presenter.BasePresenter;
import android.support.v7.app.AppCompatActivity;

public abstract class BaseActivity<V, P extends BasePresenter> extends AppCompatActivity  {
  protected    BasePresenter p;
    protected abstract  P createPresenter();

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        p = createPresenter();
        p.attachView((V)this);
    }
}
public interface ILoginView {
    void showNameError();
    void showPasswordError();
    void showProgress(int visiblity);
    void showSuccess();
    void showError(String errMsg);
}

6.LoginActivity 此处为项目入口(通常是MainActivity),展示界面,并处理触发的事件。

import android.os.Bundle;
import android.shinetech.com.finalmvpdemo.Bean.User;
import android.shinetech.com.finalmvpdemo.Presenter.UserLoginPresenter;
import android.shinetech.com.finalmvpdemo.View.BaseActivity;
import android.shinetech.com.finalmvpdemo.View.ILoginView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class LoginActivity  extends BaseActivity<LoginActivity, UserLoginPresenter > implements ILoginView {

    private ImageView err_username;
    private ImageView err_password;
    private Button btn_login;
    private EditText txt_username;
    private EditText txt_password;
    private ProgressBar progressBar;

    @Override
    protected UserLoginPresenter createPresenter() {
        return new UserLoginPresenter();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        err_username = findViewById(R.id.err_username);
        err_password = findViewById(R.id.err_password);
        txt_username = findViewById(R.id.txtUsername);
        txt_password = findViewById(R.id.txtPassword);
        btn_login = findViewById(R.id.btn_login);
        progressBar = findViewById(R.id.progressBar);

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User user = new User(txt_username.getText().toString(), txt_password.getText().toString());
                ((UserLoginPresenter)p).login(user);
            }
        });

    }
    @Override
    public void showNameError() {
        err_username.setVisibility(View.VISIBLE);
    }

    @Override
    public void showPasswordError() {

        err_password.setVisibility(View.VISIBLE);
    }

    @Override
    public void showProgress(int visiblity) {
        progressBar.setVisibility(visiblity);
    }


    @Override
    public void showSuccess() {
        err_username.setVisibility(View.INVISIBLE);
        err_password.setVisibility(View.INVISIBLE);
        progressBar.setVisibility(View.INVISIBLE);
        Toast.makeText(this, "Login success.",Toast.LENGTH_LONG).show();
    }

    @Override
    public void showError(String errMsg) {
        Toast.makeText(this,  errMsg,Toast.LENGTH_LONG).show();
    }
}

7.最后贴上activity_login.xml的layout代码 ,如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".LoginActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:textAllCaps="false"
        android:textSize="40dp"
        android:layout_margin="10dp"
        android:textAlignment="center"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:id="@+id/lblTitle"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintTop_toBottomOf="@+id/lblTitle"
        android:id="@+id/line_username"
        >

        <TextView
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Username:"
            android:textAlignment="center"
            />

        <EditText
            android:layout_weight="4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txtUsername"
            />
        <ImageView
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:src="@mipmap/x"
            android:visibility="invisible"
            android:layout_gravity="center"
            android:id="@+id/err_username"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintTop_toBottomOf="@+id/line_username"
        android:id="@+id/line_password"
        >

        <TextView
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Password:"
            android:textAlignment="center"
            />

        <EditText
            android:layout_weight="4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txtPassword"
            />
        <ImageView
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:src="@mipmap/x"
            android:visibility="invisible"
            android:layout_gravity="center"
            android:id="@+id/err_password"
            />

    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/line_password"
        android:textAlignment="center"
        >
        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/progressBar"
            android:layout_toLeftOf="@+id/btn_login"
            android:visibility="gone"
            />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn_login"
            android:textAlignment="center"
            android:text="Login"
            android:layout_centerHorizontal="true"
            />


    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值