詳細検索

How to put a nice '-' (hyphen) in a phone number on Android (java)

Avatar
by furuyamah
1 min read
Tags

How to put a nice '-' (hyphen) in a phone number on Android (java)
Translated from 日本語 • View original

What is a phone number?

[Area Code] - [Area Code] - [Customer Number]

It has a structure that separates the number with two hyphens like this.

0312345678

This is surprisingly difficult to put a hyphen on a number that does not have a hyphen.

Sometimes the area code is 2 digits, sometimes 3 digits, sometimes 4 digits, and mobile phones are 3 digits, so it's too much to do on your own.

Area code section on Wikipedia

In such a case, let's sow something long, so we use the library provided by a reliable place.
The original Google had released a library.

libphonenumber

Download

Basically, download the latest one, throw it into the libs of the Android project, and you're ready to go.

*Don't forget to check the library you want to export when creating an apk.

It is extremely easy to use.

[code lang="java" light="true"] /** * Convert a numeric phone number to a hyphened phone number * @param incomingNumber * @return Hyphened phone number */ private String getFormattedPhoneNumber(String incomingNumber) { PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); try { PhoneNumber pn = phoneUtil.parse(incomingNumber, "JP"); incomingNumber = phoneUtil.format(pn, PhoneNumberFormat.NATIONAL); } catch (NumberParseException e) { Log.e("app tag","Could not format phone number", e); } return incomingNumber; } }[/code]

I haven't tried it outside of Android, but I can use it with bare java... Maybe?

Related Articles