手機號輸入實時驗證
阿新 • • 發佈:2019-02-13
import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; /** * @author by malei on 2017/12/19. * 手機號實時驗證 */ public class PhoneFormatUtils implements TextWatcher { private EditText numberEditText; /** * 字串編輯前長度 */ int beforeLen = 0; /** * 字串編輯後長度 */int afterLen = 0; public PhoneFormatUtils(EditText numberEditText) { this.numberEditText = numberEditText; numberEditText.addTextChangedListener(this); beforeString = numberEditText.getText().toString(); } @Override public void onTextChanged(CharSequence s, int start, int before, intcount) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeLen = s.length(); } private boolean isChange = true; @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated methodif (!isChange) { isChange = true; return; } String contents = numberEditText.getText().toString(); afterLen = contents.length(); if (afterLen == 0) return; // contents = contents.replace(" ", ""); if (beforeLen > afterLen) { contents = subStringFormat(contents); } else if ((beforeLen < afterLen)) { contents = addStringFormat(contents); } if (!isChange) { numberEditText.setText(contents); if (contents.length() >= 1) numberEditText.setSelection(contents.length()); } } /** * 新增字元格式化 * * @param contents * @return */ private String addStringFormat(String contents) { // TODO Auto-generated method stub int length = contents.length(); isChange = false; if (length == 1) { if (!contents.startsWith("1")) { contents = ""; return contents; } return contents; } if (!contents.startsWith("1")) { contents = contents.substring(1); return contents; } if (!(contents.startsWith("13") || contents.startsWith("15") || contents .startsWith("18"))) { if (length > 2) { contents = "1" + contents.substring(2); } else { contents = "1"; } return contents; } if (length > 11) { contents = contents.substring(0, 11); } if (length > 3) { contents = contents.substring(0, 3) + contents.substring(3); } if (length > 7) { contents = contents.substring(0, 8) + contents.substring(8); } beforeString = contents; return contents; } /** * 記錄刪除字元之前字串內容,如若刪除後格式不符進行還原 */ private String beforeString = ""; /** * 刪除字元格式化 * * @param contents * @return */ private String subStringFormat(String contents) { // TODO Auto-generated method stub int length = contents.length(); isChange = false; if (length == 0) { return contents; } if (length == 1) { if (contents.startsWith("1")) return contents; else return beforeString; } if (length >= 2) { if (!(contents.startsWith("13") || contents.startsWith("15") || contents .startsWith("18"))) { return beforeString; } } if (length > 3) { contents = contents.substring(0, 3) + contents.substring(3); } if (length > 7) { contents = contents.substring(0, 8) + contents.substring(8); } beforeString = contents; return contents; } }