Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

android: how do I format number as phone with parentheses

I have a number that I need to format as a telephone number. If I do

 PhoneNumberUtils.formatNumber(numStr);

Then I get

888-555-1234

But what I need to get is

(888) 555-1234

How do I get the second one? Is there a standard android way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you know the country for which you want to do it, you can use Google's open source library libphonenumber . Here is how you can format it:

String numberStr = "8885551234"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
  PhoneNumber numberProto = phoneUtil.parse(numberStr, "US");
  //Since you know the country you can format it as follows:
  System.out.println(phoneUtil.format(numberProto, PhoneNumberFormat.NATIONAL));
} catch (NumberParseException e) {
  System.err.println("NumberParseException was thrown: " + e.toString());
}

If you don't know the country then for numberStr use E.164 format phone number and in place of country code use null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...