如何在editText中将regex号码电话android转换为XXX XXX XXXX

时间:2019-04-18 12:45:44

标签: android regex

我想在编辑文本中设置电话号码,例如 XXX XXX XXXX ,我的代码适用于字符:​​“-”,但不适用于“”。 请帮助

输入文本必须在线更改。

这是我的观察者

class PhoneNumberTextWatcher : TextWatcher {
private var isFormatting: Boolean = false
private var deletingHyphen: Boolean = false
private var hyphenStart: Int = 0
private var deletingBackward: Boolean = false

override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

}

override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
    if (isFormatting) {
        return
    }

    // Make sure user is deleting one char, without a selection
    val selStart = Selection.getSelectionStart(s)
    val selEnd = Selection.getSelectionEnd(s)
    if (s.length > 1 // Can delete another character
        && count == 1 // Deleting only one character
        && after == 0 // Deleting
        && (s[start].isWhitespace() || s[start] == '-' || s[start].toString().contains(" "))// a hyphen
        && selStart == selEnd) { // no selection
        deletingHyphen = true
        hyphenStart = start
        // Check if the user is deleting forward or backward
        deletingBackward = selStart == start + 1
    } else {
        deletingHyphen = false
    }
}

override fun afterTextChanged(text: Editable) {
    if (isFormatting)
        return

    isFormatting = true
    // If deleting hyphen, also delete character before or after it
    if (deletingHyphen && hyphenStart > 0) {

        if (deletingBackward) {
            if (hyphenStart - 1 < text.length) {
                text.delete(hyphenStart - 1, hyphenStart)
            }
        } else if (hyphenStart < text.length) {
            text.delete(hyphenStart, hyphenStart + 1)
        }
    }
    if (text.length == 3 || text.length == 7) {
        text.append("_")
    }
    isFormatting = false
}
}

这是我的过滤器

class PhoneNumberFilter : NumberKeyListener() {

private val patternORIGINAL2 = "^\\d{1,1}(\\d{1,1}(\\d{1,1}(( |/s|\\s|-)?(\\d{1,1}(\\d{1,1}(\\d{1,1}(( |/s|\\s|-)?(\\d{1,1}(\\d{1,1}(\\d{1,1}(\\d{1,1}?)?)?)?)?)?)?)?)?)?)?)?"

override fun getInputType(): Int {
    return InputType.TYPE_CLASS_PHONE
}

override fun getAcceptedChars(): CharArray {
    return charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', ' ')
}
override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence? {
    // Don't let phone numbers start with 1
    if (dstart == 0 && source == "-"){
        return ""
    }

    if (end > start) {
        val destTxt = dest.toString()
        val resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend)

        if (!resultingTxt.matches(patternORIGINAL.toRegex())) {
            Log.e("FilterDasha", "return2")
            return ""
        }
    }
    return null
}
}

0 个答案:

没有答案