Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a phone number using PhoneNumberUtils?

Tags:

android

How can I format a phone number using PhoneNumberUtils?

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

like image 644
Bytecode Avatar asked May 24 '11 07:05

Bytecode


People also ask

What is the correct way to format a phone number?

To format phone numbers in the US, Canada, and other NANP (North American Numbering Plan) countries, enclose the area code in parentheses followed by a nonbreaking space, and then hyphenate the three-digit exchange code with the four-digit number.

How do you format a 10-digit phone number?

If you do not want the parentheses-space-hyphen formatting (800) 555-1212 for a 10- or 11-digit number, enter a “+” before the number.

How do I fill my mobile number in international format?

Country code: +44. National destination code: 7911. Subscriber number: 123456. In total: +447911123456.


2 Answers

I opted to use google's version (https://github.com/googlei18n/libphonenumber) because then the min SDK can be lower (I think it isn't in Android SDK until 21).

Use is something like this:

PhoneNumberUtil pnu = PhoneNumberUtil.getInstance(); Phonenumber.PhoneNumber pn = pnu.parse("1234567890", "US"); String pnE164 = pnu.format(pn, PhoneNumberUtil.PhoneNumberFormat.E164); 

In Android Studio one need add this to dependencies in build.gradle:

dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])     ...     compile 'com.googlecode.libphonenumber:libphonenumber:7.2.2' } 
like image 23
sobelito Avatar answered Oct 10 '22 10:10

sobelito


At its most basic:

String formattedNumber = PhoneNumberUtils.formatNumber(unformattedNumber); 

This will automatically format the number according to the rules for the country the number is from.

You can also format Editable text in-place using:

PhoneNumberUtils.formatNumber(Editable text, int defaultFormattingType); 

Take a look at PhoneNumberUtils for more options.

like image 146
Sven Viking Avatar answered Oct 10 '22 12:10

Sven Viking