简体   繁体   中英

Android format an international phone number string with its country code included

Let's say I have this String :

String phoneNumber = "+15611234567"

Using PhoneNumberUtils.formatNumber(phoneNumber); works here and formats it into +1-561-123-4567

However , when I have a non-US phone number with its country code included , such as

String phoneNumber = "+96170123456" //Lebanese phone number

It doesn't work, it just returns it as-is instead of it being formatted.

Returns: +96170123456

Expected: +961 81-932-452 or any kind of different formatting (eg +961 70 123 456 )

In case you need it, here's the code that's not working:

public void setPhone(final String phone){
    TextView phoneTV = view.findViewById(R.id.phone);
    String formattedNumber = PhoneNumberUtils.formatNumber(phone);
    phoneTV.setText(formattedNumber);
}

The phone number's country code isn't consistent, it could be from any country.

formatNumber (String phoneNo) This method was deprecated in API level 21.

So for API level 21 or above use :

formatNumber(String phoneNumber, String defaultCountryIso)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM