Sve*_*ing 71
最基本的:
String formattedNumber = PhoneNumberUtils.formatNumber(unformattedNumber);
Run Code Online (Sandbox Code Playgroud)
这将根据该号码所在国家/地区的规则自动格式化数字.
您还可以使用以下格式对可编辑文本进行格式化:
PhoneNumberUtils.formatNumber(Editable text, int defaultFormattingType);
Run Code Online (Sandbox Code Playgroud)
看看PhoneNumberUtils
更多选项.
sob*_*ito 26
我选择使用谷歌版本(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);
Run Code Online (Sandbox Code Playgroud)
在Android Studio中,需要将其添加到build.gradle中的依赖项:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
...
compile 'com.googlecode.libphonenumber:libphonenumber:7.2.2'
}
Run Code Online (Sandbox Code Playgroud)
Mau*_*ori 16
formatNumber在LOLLIPOP上已弃用,之后您需要将语言环境添加为额外参数.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return PhoneNumberUtils.formatNumber(yourStringPhone,Locale.getDefault().getCountry());
} else {
//Deprecated method
return PhoneNumberUtils.formatNumber(yourStringPhone);
}
Run Code Online (Sandbox Code Playgroud)
看起来Google的这个库可能是在Android中进行自定义格式化的更好解决方案.
API文档:https: //github.com/googlei18n/libphonenumber/blob/master/README.md
2020年-11月
以下对我适用于所有版本的操作系统:
PhoneNumberUtils.formatNumber(yourStringPhone,Locale.getDefault().getCountry());
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
67393 次 |
最近记录: |