MVP登陆注册

来源:互联网 发布:建工金源网络培训平台 编辑:程序博客网 时间:2024/06/05 05:01

 //依赖
compile 'com.squareup.okhttp3:okhttp:3.9.0'
    compile 'org.kie.modules:com-google-code-gson:6.5.0.Final'
    compile 'com.google.code.gson:gson:2.8.2'

登录注册布局和工具

//

drawable下xml

left_item_font_selector.xml;

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:color="@color/colorRed" android:state_pressed="true"></item>    <item android:color="@color/colorBlack" android:state_pressed="false"></item></selector>
//left_item_selector.xml

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@color/colorDark" android:state_pressed="true"></item>    <item android:drawable="@color/colorWhite" android:state_pressed="false"></item></selector>
//values下的colors

colors.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <color name="colorPrimary">#3F51B5</color>    <color name="colorPrimaryDark">#303F9F</color>    <color name="colorAccent">#FF4081</color>    <color name="colorRed">#ff3660</color>    <color name="colorDark">#EEE</color>    <color name="colorWhite">#FFFFFF</color>    <color name="colorBlack">#FF262426</color></resources>
//登录布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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=".view.MainActivity">    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="40dp">        <ImageView            android:id="@+id/iv_back"            android:layout_width="20dp"            android:layout_height="20dp"            android:layout_centerVertical="true"            android:layout_marginLeft="15dp"            android:background="@drawable/dp" />        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:text="京东登陆" />    </RelativeLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="15dp"        android:orientation="horizontal">        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginRight="5dp"            android:text="账号" />        <EditText            android:id="@+id/et_phone"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_marginRight="15dp"            android:hint="手机号" />    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="15dp"        android:orientation="horizontal">        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginRight="5dp"            android:text="密码" />        <EditText            android:id="@+id/et_pwd"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_weight="1"            android:hint="请输入密码" />        <ImageView            android:id="@+id/iv_pwd"            android:layout_width="20dp"            android:layout_height="20dp"            android:layout_gravity="center_vertical"            android:layout_marginRight="15dp"            android:background="@drawable/yannormal" />    </LinearLayout>    <Button        android:id="@+id/bt_login"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="15dp"        android:text="登陆" />    <!--<TextView-->    <!--android:id="@+id/tv_register"-->    <!--android:layout_width="wrap_content"-->    <!--android:layout_height="wrap_content"-->    <!--android:layout_marginLeft="15dp"-->    <!--android:text="请注册" />-->    <Button        android:id="@+id/bt_register"        android:layout_width="80dp"        android:layout_height="wrap_content"        android:layout_marginLeft="15dp"        android:text="注册" /></LinearLayout>
//注册布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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=".view.RegisterActivity">    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="40dp">        <ImageView            android:id="@+id/iv_back"            android:layout_width="20dp"            android:layout_height="20dp"            android:layout_centerVertical="true"            android:layout_marginLeft="15dp"            android:background="@drawable/dp" />        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:text="京东注册" />    </RelativeLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="15dp"        android:orientation="horizontal">        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginRight="5dp"            android:text="账号" />        <EditText            android:id="@+id/et_phone"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_marginRight="15dp"            android:hint="手机号" />    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="15dp"        android:orientation="horizontal">        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginRight="5dp"            android:text="密码" />        <EditText            android:id="@+id/et_pwd"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_weight="1"            android:hint="请输入密码" />        <ImageView            android:id="@+id/iv_pwd"            android:layout_width="20dp"            android:layout_height="20dp"            android:layout_gravity="center_vertical"            android:layout_marginRight="15dp"            android:background="@drawable/yannormal" />    </LinearLayout>    <Button        android:id="@+id/bt_zhuce"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="15dp"        android:text="注册" /></LinearLayout>//BaseActivity  view包下的类
public class BaseActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);       ActivityStroreUtil.addActivity(this);    }}
//net包下的ActivityStroreUtil
public class ActivityStroreUtil {    private static List<Activity> list=new LinkedList<>();    public static void addActivity(Activity ac){        list.add(ac);    }    /**     * 关闭已经开启的Activity     */    public void finishAll(){        for (Activity ac:list){            if(ac != null){                ac.finish();            }        }    }}
//view包下集成BaseModel
public class BaseModel {    protected Handler handler=            new Handler(Looper.getMainLooper());}



net包

HttpUtils类

public class HttpUtils {    private static volatile HttpUtils httpUtils;    private final OkHttpClient client;    private  Context context;    private  HttpUtils(){        //1.创建OkHttpClient      client = new OkHttpClient();        this.context=context;    }    public static HttpUtils getHttpUtils(){   if(httpUtils == null){       synchronized (HttpUtils.class){           if(httpUtils==null){               httpUtils=new HttpUtils();           }       }   }        return httpUtils;    }    /**     * Get请求     */    public void doGet(String url, Callback callback){        //判断是否有网        if (NetworkUtils.isAvailable(context)){            //网络不可用            Toast.makeText(context, "网络不可用", Toast.LENGTH_SHORT).show();            return;        }        //创建一个Request        Request request=new Request.Builder().url(url).build();        //发送请求        client.newCall(request).enqueue(callback);    }    /**     * POST请求     *     * @param url     * @param params     * @param callback     */    public void doPost(String url, Map<String,String> params,Callback callback){        //这里可以加网络判断        //判断参数        if(params == null || params.size() == 0){            throw new RuntimeException("params is null!!!");        }        //创建一个请求        FormBody.Builder builder=new FormBody.Builder();     for(Map.Entry<String,String> entry:params.entrySet()){         builder.add(entry.getKey(),entry.getValue());     }        FormBody formBody=builder.build();        Request request=new Request.Builder().url(url).post(formBody).build();        //发送请求        client.newCall(request).enqueue(callback);    }}
OnNetListenter类
public interface OnNetListenter<T> {    //成功回调    public void OnSuccess(T t);    //失败回调    public void OnFailure(Exception e);}
Api类
public class Api {    public static boolean isOnline=false;    public static final String DEV="http://120.27.23.105/";    public static final String WORK="";    public static final String HOST=isOnline ? WORK : DEV;    public  static final String LOGIN=HOST+"user/login";//登陆    public static final String REGISTER=HOST+"user/reg";//注册;    }


model层登录注册都要继承的类

public class BaseModel {    protected Handler handler=            new Handler(Looper.getMainLooper());}

model层接口登陆

public interface ILoginModel { //Get请求    //Post请求    public void login(String account, String pwd, OnNetListenter<LoginBean> onNetListenter);}
model层登录接口

public class LoginModel extends BaseModel implements ILoginModel {    @Override    public void login(String account, String pwd, final OnNetListenter<LoginBean> onNetListenter) {        Map<String,String> params=new HashMap<>();        params.put("mobile",account);        params.put("password",pwd);        HttpUtils.getHttpUtils().doPost(Api.LOGIN, params, new Callback() {            @Override            public void onFailure(Call call, final IOException e) {               handler.post(new Runnable() {                   @Override                   public void run() {                       onNetListenter.OnFailure(e);                   }               });            }            @Override            public void onResponse(Call call, Response response) throws IOException {                String string=response.body().string();                final LoginBean loginBean=new Gson().fromJson(string,LoginBean.class);                handler.post(new Runnable() {                    @Override                    public void run() {                        onNetListenter.OnSuccess(loginBean);                    }                });            }        });    }}
//model层注册

public interface IRegisterModel {    public void register(String account, String pwd, OnNetListenter<BaseBean> onNetListenter);}

//model层注册接口

public class RegisterModel extends BaseModel implements IRegisterModel {    @Override    public void register(String account, String pwd, final OnNetListenter<BaseBean> onNetListenter) {        Map<String,String> params=new HashMap<>();        params.put("mobile",account);        params.put("password",pwd);        HttpUtils.getHttpUtils().doPost(Api.REGISTER, params, new Callback() {            @Override            public void onFailure(Call call, final IOException e) {                handler.post(new Runnable() {                    @Override                    public void run() {                        onNetListenter.OnFailure(e);                    }                });            }            @Override            public void onResponse(Call call, Response response) throws IOException {                String string = response.body().string();                 final BaseBean baseBean= new Gson().fromJson(string,BaseBean.class);             handler.post(new Runnable() {                 @Override                 public void run() {                     onNetListenter.OnSuccess(baseBean);                 }             });            }        });    }} //登录presenter层
public class MainPresenter {    private IMainActivity iMainActivity;    private final ILoginModel iLoginModel;    public MainPresenter(IMainActivity iMainActivity) {     this.iMainActivity=iMainActivity;    iLoginModel=new LoginModel();    }    public void login(){        String account=iMainActivity.getAccount();        String pwd=iMainActivity.getPwd();        //判断账号密码是否正确        if (checkAccount(account) && checkPwd(pwd)) {            //去调用model,进行登陆            iLoginModel.login(account, pwd, new OnNetListenter<LoginBean>() {                @Override                public void OnSuccess(LoginBean loginBean) {                    //保存登陆成功后的数据,可以保存到SP,也可以保存到数据库                    iMainActivity.show(loginBean.getMsg());                    //跳转到分类界面                    iMainActivity.toClassAc();                }                @Override                public void OnFailure(Exception e) {                }            });        }    }    private boolean checkPwd(String pwd) {        if(TextUtils.isEmpty(pwd)){            //给用户提示,输入的账号不能为空            iMainActivity.show("请输入的账号不能为空");            return  false;        }        if(pwd.length() !=6){            iMainActivity.show("请输入6位数密码");            return false;        }        return true;    }    /**     * 验证手机号是否正确     *     * @param account     */    private boolean checkAccount(String account) {     if (TextUtils.isEmpty(account)){         //给用户提示,输入的账号不能为空         iMainActivity.show("请输入账号");         return  false;     }        if (!isMobileNO(account)) {            iMainActivity.show("请输入正确的手机号");            return false;        }        return true;    }    /*  判断是否是手机号   */    public static boolean isMobileNO(String mobiles) {        Pattern p = Pattern.compile("^(13[0-9]|14[57]|15[0-35-9]|17[6-8]|18[0-9])[0-9]{8}$");        Matcher m = p.matcher(mobiles);        return m.matches();    }    public void register() {        //其实就是跳转到注册页面        iMainActivity.toRegisterAc();    }}
//presenter层注册
public class RegisterPresenter {    private IRegisterActivity iRegisterActivity;     private IRegisterModel iRegisterModel;    public RegisterPresenter(IRegisterActivity iRegisterActivity) {    this.iRegisterActivity=iRegisterActivity;     iRegisterModel=new RegisterModel();    }    private boolean checkPwd(String pwd) {        if (TextUtils.isEmpty(pwd)) {            //给用户提示,输入的账号不能为空            iRegisterActivity.show("请输入密码");            return false;        }        if (pwd.length() != 6) {            iRegisterActivity.show("请输入6位密码");            return false;        }        return true;    }    /**     * 验证手机号是否正确     *     * @param account     */    private boolean checkAccount(String account) {        if (TextUtils.isEmpty(account)) {            //给用户提示,输入的账号不能为空            iRegisterActivity.show("请输入账号");            return false;        }        if (!isMobileNO(account)) {            iRegisterActivity.show("请输入正确的手机号");            return false;        }        return true;    }    /*    判断是否是手机号     */    public static boolean isMobileNO(String mobiles) {        Pattern p = Pattern.compile("^(13[0-9]|14[57]|15[0-35-9]|17[6-8]|18[0-9])[0-9]{8}$");        Matcher m = p.matcher(mobiles);        return m.matches();    }    //注册    public void register(){       String account=iRegisterActivity.getAccount();        String pwd = iRegisterActivity.getPwd();     if(checkAccount(account) && checkPwd(pwd)){         iRegisterModel.register(account, pwd, new OnNetListenter<BaseBean>() {             @Override             public void OnSuccess(BaseBean baseBean) {                 //成功以后,回到登陆界面                 if(baseBean.getCode().equals("1")){                     iRegisterActivity.show(baseBean.getMsg());                 }else{                     iRegisterActivity.show(baseBean.getMsg());                      //跳转页面时销毁本界面                     iRegisterActivity.finishAc();                 }             }             @Override             public void OnFailure(Exception e) {             }         });     }    }}
//登录view层接口
public interface IMainActivity {    public String getAccount();   public String getPwd();    public void show(String str);    public void toRegisterAc();  }
//注册view层接口
public interface IRegisterActivity {public String getAccount();    public String getPwd();    public void finishAc();    public void show(String str);
    public void toRegisterAc();
   //这个是登陆成功跳转页面的方法   public void toClassAc();
}
//登录view层继承接口
public class MainActivity extends BaseActivity implements IMainActivity, View.OnClickListener {    private ImageView mBackIv;    private EditText mPhoneEt;    private EditText mPwdEt;    private ImageView mPwdIv;    private Button mLoginBt;    private Button bt_register;    private MainPresenter mainPresenter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //关联presenter        mainPresenter = new MainPresenter(this);        initView();    }    private void initView() {        mBackIv = (ImageView) findViewById(R.id.iv_back);        mPhoneEt = (EditText) findViewById(R.id.et_phone);        mPwdEt = (EditText) findViewById(R.id.et_pwd);        mPwdIv = (ImageView) findViewById(R.id.iv_pwd);        mLoginBt = (Button) findViewById(R.id.bt_login);        mLoginBt.setOnClickListener(this);        bt_register = (Button) findViewById(R.id.bt_register);        bt_register.setOnClickListener(this);    }        
        //重写登录成功后跳转的方法
      @Override    public void toClassAc() {        Intent intent = new Intent(MainActivity.this, ClassActivity.class);        startActivity(intent);    }
    @Override    public String getAccount() {        return mPhoneEt.getText().toString().trim();    }    @Override    public String getPwd() {        return mPwdEt.getText().toString().trim();    }    @Override    public void show(String str) {        Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();    }    //跳转页面的方法    @Override    public void toRegisterAc() {        Intent intent = new Intent(MainActivity.this, RegisterActivity.class);        startActivity(intent);    }       @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.bt_login:                mainPresenter.login();                break;            case R.id.bt_register://                注册               mainPresenter.register();                break;        }    }}


//注册view层继承接口

public class RegisterActivity extends AppCompatActivity implements IRegisterActivity, View.OnClickListener {    private ImageView mBackIv;    private EditText mPhoneEt;    private EditText mPwdEt;    private ImageView mPwdIv;    private Button mLoginBt;   private RegisterPresenter registerPresenter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_register);        registerPresenter = new RegisterPresenter(this);        initView();    }    private void initView() {        mBackIv = (ImageView) findViewById(R.id.iv_back);        mPhoneEt = (EditText) findViewById(R.id.et_phone);        mPwdEt = (EditText) findViewById(R.id.et_pwd);        mPwdIv = (ImageView) findViewById(R.id.iv_pwd);        mLoginBt = (Button) findViewById(R.id.bt_zhuce);        mLoginBt.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.bt_zhuce:                //这个按钮是注册                registerPresenter.register();                break;            default:                break;        }    }    @Override    public String getAccount() {        return mPhoneEt.getText().toString().trim();    }    @Override    public String getPwd() {        return mPwdEt.getText().toString().trim();    }  //销毁本页面    @Override    public void finishAc() {     finish();    }    @Override    public void show(String str) {        Toast.makeText(RegisterActivity.this, str, Toast.LENGTH_SHORT).show();    }}


原创粉丝点击