Android EditText 手机号344格式化输入的最佳实现

PhoneTextWatcher

手机号格式化监听器,支持普通输入/删除,中间输入/删除,在任意位置下黏贴/剪贴多个数字等多种交互场景。

目前支持的手机号格式为 3-4-4 分隔符可以自定义

Preview

gif_phone_text_watcher.gif

How to get

Step 1. Add the JitPack repository to your build file

Add it in your root build.gradle at the end of repositories:

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

Step 2. Add the dependency

dependencies {
    implementation 'com.github.jaydroid1024:PhoneTextWatcher:0.0.2'
}

How to use

val editTextSpace = findViewById(R.id.editText_space)
val textViewSpace = findViewById(R.id.textView_space)
// 缺省分隔符为空格
val phoneTextWatcherSpace = PhoneTextWatcher()
editTextSpace.addTextChangedListener(phoneTextWatcherSpace)
// 设置格式化输入的回调
phoneTextWatcherSpace.setTextChangedCallback(object : TextChangeCallback() {
    override fun afterTextChanged(s: String?, isPhoneNumberValid: Boolean) {
        textViewSpace.text = "反格式化后的手机号为:$s \n是否是有效的手机号:$isPhoneNumberValid"
    }
})

val editTextLine = findViewById(R.id.editText_line)
val textViewLine = findViewById(R.id.textView_line)
// 指定分隔符为横线,或者你传入的字符
val phoneTextWatcherLine = PhoneTextWatcher(AsYouTypeFormatter.SEPARATOR_LINE)
editTextLine.addTextChangedListener(phoneTextWatcherLine)
// 设置格式化输入的回调
phoneTextWatcherLine.setTextChangedCallback(object : TextChangeCallback() {
    override fun afterTextChanged(s: String?, isPhoneNumberValid: Boolean) {
        textViewLine.text = "反格式化后的手机号为:$s \n是否是有效的手机号:$isPhoneNumberValid"
    }
})

Go to

Github

你可能感兴趣的:(Android EditText 手机号344格式化输入的最佳实现)