EditText 自动格式化电话电话号码
需要格式化的格式为:xxx xxxx xxxx
有两种方式:1.为监听当前输入的长度,当长度为第四位,九位的时候,在原内容上追加空格。(from stackOverFlow)2.每次输入后,格式化当前内容。
方式一:
public class PhoneEditText extends EditText implements TextWatcher { int beforeLen = 0; int afterLen = 0; public PhoneEditText(Context context) { super(context); setInputType(InputType.TYPE_CLASS_PHONE); setFilters(new InputFilter[]{new InputFilter.LengthFilter(13)}); addTextChangedListener(this); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { beforeLen = s.length(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { String txt = s.toString(); if (txt.isEmpty()) return; afterLen = s.length(); if (afterLen > beforeLen) { if (afterLen == 4 || afterLen == 9) { setText(new StringBuffer(txt).insert(txt.length() - 1, " ").toString()); } } else { if (txt.endsWith(" ") && (afterLen == 9 || afterLen == 4)) { setText(new StringBuffer(txt).delete(afterLen - 1, afterLen).toString()); } } setSelection(afterLen); } public String getPhoneNumber() { CharSequence text = super.getText(); return text.toString().replaceAll(" ", ""); } public String getOriginalNumber() { return getText().toString(); } }
第二种方法:
public class PhoneEditText extends EditText implements TextWatcher { public PhoneEditText(Context context) { super(context); setInputType(InputType.TYPE_CLASS_PHONE); setFilters(new InputFilter[]{new InputFilter.LengthFilter(13)}); addTextChangedListener(this); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { String txt = getPhoneNumber(); if (txt.isEmpty()) return; flag = !flag; if (flag) { String result = getFormatString(txt); setText(result); setSelection(result.length()); } } boolean flag = false; private String getFormatString(String str) { String result; if (str.length() > 7) { result = str.substring(0, 3) + " " + str.substring(3, 7) + " " + str.substring(7, str.length()); } else if (str.length() > 3) { result = str.substring(0, 3) + " " + str.substring(3, str.length()); } else { result = str; } return result; } public String getPhoneNumber() { CharSequence text = super.getText(); return text.toString().replaceAll(" ", ""); } public String getOriginalNumber() { return getText().toString(); } }
ps:第一种方法如果不按顺序输入,格式化不了。
第二种方法有待验证。