该方法主要使用Google开源的libphonenumber库实现,能实现所有国家的号码格式。
1.导入依赖
在 build.gradle 中添加如下依赖
implementation "com.googlecode.libphonenumber:libphonenumber:8.12.54"
2. 开始使用
在你的Composable函数中使用的TextField中添加visualTransformation属性,注意code为国家码,例如(中国大陆86、中国香港852等)。
TextField(
value = text,
onValueChange = onValueChange,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Phone
),
visualTransformation = PhoneNumberVisualTransformation(code))
添加一个PhoneNumberVisualTransformation文件如下:
// 参数为国家码
class PhoneNumberVisualTransformation(val countryCode: Int) :
VisualTransformation {
private val phoneNumberUtil = PhoneNumberUtil.getInstance()
private val country =
CountryCodeToRegionCodeMap.getCountryCodeToRegionCodeMap()[countryCode]?.get(0)
private val formatter = phoneNumberUtil.getAsYouTypeFormatter(country)
override fun filter(text: AnnotatedString): TransformedText {
var formatResult = text.text
formatter.clear()
text.text.toCharArray().forEachIndexed { index, ch ->
formatResult = formatter.inputDigit(ch)
}
return TransformedText(
AnnotatedString(formatResult), object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
val newOffset = formatResult.length
return newOffset
}
override fun transformedToOriginal(offset: Int): Int {
val newOffset = formatResult.length
return newOffset
}
}
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is PhoneNumberVisualTransformation) return false
if (countryCode != other.countryCode) return false
return true
}
override fun hashCode(): Int {
return countryCode.hashCode()
}
companion object {
const val TAG = "PhoneNumberVisualTransformation"
}
}
3. 参考
[libphonenumebr] : https://github.com/google/libphonenumber