EditText电话号码格式

来源:互联网 发布:迅雷5.8绿色优化版 编辑:程序博客网 时间:2024/05/25 19:56
看了网上一些文章,自己改了改,小白<img alt="奋斗" src="http://static.blog.csdn.net/xheditor/xheditor_emot/default/struggle.gif" />
/** *  * @author Damon * 电话格式EditText */public class PhoneNumberEditText extends EditText implements TextWatcher {public PhoneNumberEditText(Context context, AttributeSet attributeSet) {super(context, attributeSet);}public PhoneNumberEditText(Context context, AttributeSet attributeSet,int defStyle) {super(context, attributeSet, defStyle);}public PhoneNumberEditText(Context context) {super(context);setInputType(InputType.TYPE_CLASS_PHONE);//setFilters(new InputFilter[] { new InputFilter.LengthFilter(13) });addTextChangedListener(this);}@Overridepublic void afterTextChanged(Editable s) {     System.out.print(s);}public String getFormatString(String text) {String result = "";if (text.length() == 8) {if (text.length() > 4) {result = text.substring(0, 4) + " "+ text.substring(4, text.length());}} else if (text.length() == 11) {if (text.length() > 7) {result = text.substring(0, 3) + " " + text.substring(3, 7)+ " " + text.substring(7, text.length());} else if (text.length() > 3) {result = text.substring(0, 3) + " "+ text.substring(3, text.length());}} else {result = text;}return result;}boolean flag=false;public String getPhoneNumber() {CharSequence text = super.getText();return text.toString().replaceAll(" ", "");}public String getOriginalNumber() {return getText().toString();}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,int after) {}@Overridepublic void onTextChanged(CharSequence s, int start, int count, int after) {String text = getPhoneNumber();if (TextUtils.isEmpty(text)) {return;}if (text.length()>13) {text=(String) text.subSequence(0, 13);}flag=!flag;if (flag) {String result = getFormatString(text);setText(result);setSelection(result.length());}}}


0 0
原创粉丝点击