写一个手机号344(xxx xxxx xxxx)格式方法

/**
 * 电话3 4 4格式(即:xxx xxxx xxxx)
 * 电话长度11位数字
 * @param view 输入框
 * @param text 文本
 */
public static void onTextChanged344(EditText view, String text) {
    if (view== null || text == null || text.length() == 0) return;
    char space = ' ';
    int indexSpace1 = 3;
    int indexSpace2 = 8;
    StringBuilder sb = new StringBuilder();
    //1.取出所有字符,去掉' '和非法字符
    for (int i = 0; i < text.length(); i++) {
        //如果数字数大于11位,去掉后面的数字
        if(sb.length() >= 11){
            break;
        }

        //是否合法字符(0~9)
        Pattern pattern = Pattern.compile("^[0-9]*$");
        Matcher matcher = pattern.matcher(String.valueOf(text.charAt(i)));
        if (text.charAt(i) != space && matcher.matches()) {
            sb.append(text.charAt(i));
        }
    }

    //2.根据长度追加' '
    if(sb.length() > indexSpace1){
        sb.insert(indexSpace1, space);
    }
    if(sb.length() > indexSpace2){
        sb.insert(indexSpace2, space);
    }
    //3.设置文本和光标位置
    if(!sb.toString().equals(text)){
        view.setText(sb.toString());
        view.setSelection(sb.length());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值