How to format a phone number using PhoneNumberUtils?

前端 未结 8 1885
慢半拍i
慢半拍i 2020-12-07 22:05

How can I format a phone number using PhoneNumberUtils?

E.g.: 1234567890(123) 456-7890

相关标签:
8条回答
  • 2020-12-07 22:59

    2020 working sulotion:

    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    
    String countryIso = telephonyManager.getNetworkCountryIso().toUpperCase();              //important!!
    
    phoneNumberTextView.setText(PhoneNumberUtils.formatNumber("3473214567", countryIso));
    
    0 讨论(0)
  • 2020-12-07 23:05

    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)
        }
    }
    
    0 讨论(0)
提交回复
热议问题