How can I format a phone number using PhoneNumberUtils?
E.g.: 1234567890
→ (123) 456-7890
2020 working sulotion:
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String countryIso = telephonyManager.getNetworkCountryIso().toUpperCase(); //important!!
phoneNumberTextView.setText(PhoneNumberUtils.formatNumber("3473214567", countryIso));
Standalone solution for format raw phone number, if you don`t know your country and need support on pre-lollipop.
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)
}
}