310. Android 输入手机号码自动空格

/**
 * 去除空格,回车,换行符,制表符
 *
 * @param str
 * @return
 */
public static String replaceBlank(String str) {
    String dest = "";
    if (str != null) {
        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(str);
        if (m.find()) {
            dest = m.replaceAll("");
        }
    }
    return dest;
}




/**
 * 设置EditText输入手机号自动空格(注:需求是130 1234 4567,中间第4个数字和第8个数字空格前面加空格)
 *
 * @param s
 */
public static String setPhoneBlank(String s) {
    try {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (i != 3 && i != 8 && s.charAt(i) == ' ') {
                continue;
            } else {
                sb.append(s.charAt(i));
                if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                    sb.insert(sb.length() - 1, ' ');
                }
            }
        }
        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return s;
    }
}

/**
 * 监听onTextChanged时使用
 *
 * @param s
 * @param start
 * @param before
 * @param count
 * @throws Exception
 */
public static void setPhoneBlank(EditText editText, Editable s, int start, int before, int count) throws Exception {
    if (s == null || s.length() == 0) return;

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < s.length(); i++) {
        if (i != 3 && i != 8 && s.charAt(i) == ' ') {
            continue;
        } else {
            sb.append(s.charAt(i));
            if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                sb.insert(sb.length() - 1, ' ');
            }
        }
    }

    if (!sb.toString().equals(s.toString())) {
        int index = start + 1;
        if (sb.charAt(start) == ' ') {
            if (before == 0) {
                index++;
            } else {
                index--;
            }
        } else {
            if (before == 1) {
                index--;
            }
        }
        editText.setText(sb.toString());
        editText.setSelection(index);
    }

    String content = replaceBlank(s.toString());
    if (content.length() == 11) {
        editText.setSelection(s.length());
    }
}
public boolean isPass = false;
phoneEt.setOnTextChangedListener(new CommonEditText.OnTextChangedListener() {
    @Override
    public void onTextChanged(Editable s, int start, int before, int count) {
        if (!isPass) {
            try {
                StringUtils.setPhoneBlank(phoneEt.getEditText(), s, start, before, count);
            } catch (Exception e) {
                e.printStackTrace();
                isPass = true;
            }
        }
    }
});

 

 

 

 

 

 

 

上一篇:小美的仓库整理(美团2020秋招笔试题)之为什么不能用线段解题


下一篇:剑指 Offer 50. 第一个只出现一次的字符