先来效果图:
设置手机格式化操作只需要设置EditText的addTextChangedListener的监听,下面看代码
/*editText输入监听*/ et_activity_up_login_phone.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s == null || s.length() == 0) return; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if (i != 3 && i != 8 && s.charAt(i) == '-') { continue; } else { sb.append(s.charAt(i)); if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != '-') { sb.insert(sb.length() - 1, '-'); } } } if (!sb.toString().equals(s.toString())) { int index = start + 1; if (sb.charAt(start) == '-') { if (before == 0) { index++; } else { index--; } } else { if (before == 1) { index--; } } et_activity_up_login_phone.setText(sb.toString()); et_activity_up_login_phone.setSelection(index); } } @Override public void afterTextChanged(Editable editable) { //获取没有-的手机号 endPhone = et_activity_up_login_phone.getText().toString().replace("-", ""); if (endPhone.length() == 11) {//如果最后的 号码为11位 //判断手机号是否正确 if (!Tool.isPhoneNum(endPhone)) { Toast.makeText(UpLoginActivity.this, "请输入正确的手机号:" + endPhone, Toast.LENGTH_SHORT).show(); } else { //改变获取验证码字体颜色 tv_activity_up_login_djs.setTextColor(Color.parseColor("#64aaff"));//高亮,可以点击 djsType = true;//设置验证码为可点击状态 tv_activity_up_login_djs.setClickable(true); } } } }); }