获取国家/地区的货币代码

时间:2012-02-06 10:04:20

标签: java android location locale currency

我在获取国家/地区的货币代码时遇到问题。我的任务是获取用户的位置,找出他现在所在的国家/地区并获取该国家/地区的货币代码。以下是从获取的位置获取国家/地区名称和国家/地区代码的代码:

Geocoder gc = new Geocoder(this);
List<Address> addresses = gc.getFromLocation(
                location.getLatitude(), location.getLongitude(), 5);

textView1.setText(addresses.get(0).getCountryName());
textView2.setText(addresses.get(0).getCountryCode());

这完全没问题。现在我应该使用java.util.Currency类来获取Currency对象。我可以使用Currency.getInstance(Locale locale)方法。但是Locale类中没有构造函数只允许将国家/地区代码作为参数传递。意味着我无法为该国家/地区创建Locale个对象。怎么解决这个问题?提前致谢。

4 个答案:

答案 0 :(得分:5)

如果国家/地区代码无效,您应该能够使用Currency.getInstance(new Locale("",code)),并可能出现例外情况。

答案 1 :(得分:1)

String lang = Locale.getDefault().getDisplayLanguage();
Locale locale = new Locale(lang, COUNTRY_YOU_HAVE);

答案 2 :(得分:0)

为什么不使用Address对象来获取Locale,方法是:

http://developer.android.com/reference/android/location/Address.html#getLocale%28%29

答案 3 :(得分:0)

请记住,由于我们没有Language Code,这样做的结果将是不准确的,或者由于系统上没有该Locale,它甚至可能引发异常。 相反,我会按照以下步骤进行搜索:

val locale = Locale.getAvailableLocales().first { it.country == address.countryCode }
val currency = Currency.getInstance(locale)

此外,如果您想尽可能地准确,可以执行以下操作:

val locale =
    Locale.getAvailableLocales().firstOrNull { it.country.equals(countryCode, true) && it.language.equals(countryCode, true) }
        ?: Locale.getAvailableLocales().firstOrNull { it.country.equals(countryCode, true) }
        ?: Locale.getDefault()
val currency = Currency.getInstance(locale)