EditText电话号码格式

看了网上一些文章,自己改了改,小白<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);
	}

	@Override
	public 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();
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值