如何解决如何使用PhoneNumberUtils格式化电话号码?
| 如何使用PhoneNumberUtils格式化电话号码? 例如:1234567890
→(123) 456-7890
解决方法
最基本的:
String formattedNumber = PhoneNumberUtils.formatNumber(unformattedNumber);
这将根据号码所属国家/地区的规则自动格式化该号码。
您还可以使用以下方法就地设置可编辑文本的格式:
PhoneNumberUtils.formatNumber(Editable text,int defaultFormattingType);
请看PhoneNumberUtils
了解更多选项。
,我选择使用Google的版本(https://github.com/googlei18n/libphonenumber),因为这样最小的SDK可能会更低(我认为直到21点才在Android SDK中使用)。
使用是这样的:
PhoneNumberUtil pnu = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber pn = pnu.parse(\"1234567890\",\"US\");
String pnE164 = pnu.format(pn,PhoneNumberUtil.PhoneNumberFormat.E164);
在Android Studio中,需要将其添加到build.gradle中的依赖项中:
dependencies {
compile fileTree(dir: \'libs\',include: [\'*.jar\'])
...
compile \'com.googlecode.libphonenumber:libphonenumber:7.2.2\'
}
,在LOLLIPOP上已弃用formatNumber,此后需要将语言环境添加为额外的参数。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return PhoneNumberUtils.formatNumber(yourStringPhone,Locale.getDefault().getCountry());
} else {
//Deprecated method
return PhoneNumberUtils.formatNumber(yourStringPhone);
}
,看来Google提供的这个库可能是在Android中进行自定义格式的更好的解决方案。
API文档:
https://github.com/googlei18n/libphonenumber/blob/master/README.md
,用于格式化原始电话号码的独立解决方案,如果您不知道您所在的国家/地区并且需要棒棒糖之前的支持。
fun formatNumberCompat(rawPhone: String?,countryIso: String = \"\"): String {
if (rawPhone == null) return \"\"
var countryName = countryIso
if (countryName.isBlank()) {
countryName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Resources.getSystem().configuration.locales[0].country
} else {
Resources.getSystem().configuration.locale.country
}
}
return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
PhoneNumberUtils.formatNumber(rawPhone)
} else {
PhoneNumberUtils.formatNumber(rawPhone,countryName)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。