【问题标题】:Acquiring a country's currency code获取一个国家的货币代码
【发布时间】:2012-02-06 10:04:20
【问题描述】:

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

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 对象。如何解决?提前致谢。

【问题讨论】:

  • 有一个构造函数Locale(String language, String country)符合ISO-639语言组。
  • 区域设置(字符串语言,字符串国家)?

标签: java android location locale currency


【解决方案1】:

您应该可以使用Currency.getInstance(new Locale("",code)),如果国家/地区代码无效,则可能会出现异常。

【讨论】:

    【解决方案2】:
    String lang = Locale.getDefault().getDisplayLanguage();
    Locale locale = new Locale(lang, COUNTRY_YOU_HAVE);
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 你不应该这样做,因为getLocale()返回系统默认Locale,它被传递给Geocoder实例,所以它总是返回设备默认国家。
      【解决方案4】:

      请记住,这样做的结果将是不准确的,因为我们没有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)
      

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 1970-01-01
        • 2017-04-09
        • 1970-01-01
        • 1970-01-01
        • 2015-03-07
        • 1970-01-01
        • 1970-01-01
        • 2011-08-10
        相关资源
        最近更新 更多