android:如何将数字格式化为带括号的电话 [英] android: how do I format number as phone with parentheses

查看:129
本文介绍了android:如何将数字格式化为带括号的电话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个号码需要格式化为电话号码.如果我愿意

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

 PhoneNumberUtils.formatNumber(numStr);

然后我得到

888-555-1234

但是我需要得到的是

(888) 555-1234

如何获得第二个?有标准的android方式吗?

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

推荐答案

如果您知道要使用的国家/地区,则可以使用Google的开放源代码库

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());
}

如果您不知道国家/地区,则对于numberStr,请使用 E.164格式的电话号码并使用国家/地区代码代替null.

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

这篇关于android:如何将数字格式化为带括号的电话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆