RxBinding实现用户注册验证

一,引入依赖

微信图片_20190515142625.png

二,设计布局
使用了TextInputLayout


微信图片_20190515143009.png

LinearLayout的约束布局比例

微信图片_20190515145037.png

三,代码实现

public class RegisterActivity extends AppCompatActivity {
  private volatile int regInfo = 1;
  @OnClick(R.id.backthis)
  public void backto() {
    finish();
  }
  @BindView(R.id.et_userNm)
  EditText et_userNm;
  @BindView(R.id.et_pwd)
  EditText et_pwd;
  @BindView(R.id.et_confimePwd)
  EditText et_confirmPwd;
  @BindView(R.id.btn_register)
  Button btn_register;
  @BindView(R.id.lay_userNm)
  TextInputLayout lay_userNm;
  @BindView(R.id.lay_pwd)
  TextInputLayout lay_pwd;
  @BindView(R.id.lay_confirmPwd)
  TextInputLayout lay_confirmPwd;
  @OnClick(R.id.btn_register)
  public void do_register(){
      /*此处省略提交网站Api写入数据库的逻辑*/

      Toast toast = Toast.makeText(RegisterActivity.this, "注册成功,即将跳转登录", Toast.LENGTH_SHORT);
      toast.setGravity(Gravity.CENTER,0,0);
      toast.show();
      //EventBus在此处发送RegIntoEntity,LoginActivity使用EventBus接受这个RegIntoEntity,并填充登录框
      EventBus.getDefault().post(new RegIntoEntity(et_userNm.getText().toString(),et_pwd.getText().toString()));
      //延迟2秒关闭 RegisterActivity
      Observable.timer(2, TimeUnit.SECONDS).subscribe(new Consumer() {
           @Override
           public void accept(Long aLong) throws Exception {
                  finish();
           }
      });
  }

  @SuppressLint("CheckResult")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    ButterKnife.bind(this);

    RxTextView.textChanges(et_userNm).subscribe(new Consumer() {
        @Override
        public void accept(CharSequence charSequence) throws Exception {
             if (!String.valueOf(charSequence).equals("")) {
                if (!checkUserNm(String.valueOf(charSequence))) {
                    lay_userNm.setError("用户名仅能包含字母、数字、下划线,长度6-10位");
                } else {
                    //异步验证用户名是否已被注册,并更新UI
                    validateUserNm(String.valueOf(charSequence));
                }
             } else {
                 lay_userNm.setError("");
             }
        }
    });

    RxTextView.textChanges(et_pwd).subscribe(new Consumer() {
        @Override
        public void accept(CharSequence charSequence) throws Exception {
            if (!String.valueOf(charSequence).equals("")) {
                if (!checkPwd(String.valueOf(charSequence))) {
                    lay_pwd.setError("密码仅能包含字母、数字、下划线,长度6-12位");
                } else {
                    lay_pwd.setError("");
                }
            } else {
                lay_pwd.setError("");
            }
        }
    });

    RxTextView.textChanges(et_confirmPwd).subscribe(new Consumer() {
        @Override
        public void accept(CharSequence charSequence) throws Exception {
            if (!et_pwd.getText().toString().equals("")) {
                if (!String.valueOf(charSequence).equals(et_pwd.getText().toString())) {
                    lay_confirmPwd.setError("两次输入密码不一致!");
                } else {
                    lay_confirmPwd.setError("");
                }
            } else {
                lay_confirmPwd.setError("");
            }
        }
    });

    Observable
            .combineLatest(
                    RxTextView.textChanges(et_userNm).map(CharSequence::toString),
                    RxTextView.textChanges(et_pwd).map(CharSequence::toString),
                    RxTextView.textChanges(et_confirmPwd).map(CharSequence::toString),
                    new Function3(){
                        @Override
                        public Boolean apply(String s1, String s2,String s3) throws Exception {
                            return checkUserNm(s1) && checkPwd(s2) && checkConfirmPwd(s3);
                        }
                    }
            ).subscribe(new Consumer() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean){
                        btn_register.setEnabled(true);
                    } else {
                        btn_register.setEnabled(false);
                    }
                }
    });

}

private boolean checkUserNm (String strUserNm){
    //6-10个字符,至少1个字母和1个数字:
    return strUserNm.matches("^[a-z][a-zA-Z0-9]{5,9}$");
   
}

private boolean checkPwd (String strPwd){
    //6-12个字符,至少1个字母和1个数字:
    return strPwd.matches("^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z\\d]{5,11}$");
}

private boolean checkConfirmPwd(String confirmPwd){
    return confirmPwd.equals(et_pwd.getText().toString());
}

private void validateUserNm(String loginName) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            OkHttpClient client = new OkHttpClient();
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("loginName",loginName);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            RequestBody body = RequestBody.create(WebUtil.mediaType, String.valueOf(jsonObject));
            Request request = new Request.Builder()
                    .url(WebUtil.BASEURL + WebUtil.checkUserNm)
                    .post(body)
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()){
                        String result = response.body().string();
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(result);
                            regInfo = jsonObject.getInt("status");
                            if (regInfo == -1) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        lay_userNm.setError(loginName + "已被使用");
                                    }
                                });
                            } else if (regInfo == 1){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        lay_userNm.setError("");
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }).start();
}

}

你可能感兴趣的:(RxBinding实现用户注册验证)