How to format a phone number using PhoneNumberUtils?

前端 未结 8 1917
慢半拍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:45

    We can easily do this by:

    val tm = act.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
    val formattedPhoneNumber= PhoneNumberUtils.formatNumber(phone, tm?.simCountryIso?.toUpperCase())
    

    here, tm?.simCountryIso?.toUpperCase() returns iso code, "in" in my case and we used toUpperCase() to convert it into "IN"

    you can also use networkCountryIso instead of simCountryIso.

    From doc:

    getNetworkCountryIso(): Returns the ISO-3166-1 alpha-2 country code equivalent of the MCC (Mobile Country Code) of the current registered operator or the cell nearby, if available.

    getSimCountryIso(): Returns the ISO-3166-1 alpha-2 country code equivalent for the SIM provider's country code.

    you can also pass direct iso code, for example:

    PhoneNumberUtils.formatNumber("2025550739", "US") // output: (202) 555-0739
    

    Check the list of iso codes.

提交回复
热议问题