【问题标题】:Address formatting based on locale in androidandroid中基于语言环境的地址格式
【发布时间】:2016-12-03 15:58:23
【问题描述】:

嗨,在我的应用程序中,我需要根据用户设置的区域设置显示输入地址。有没有人在 Android 平台上工作或地址格式或有任何指针。

【问题讨论】:

  • 我能知道这个问题 -1 评分的原因吗?

标签: android street-address


【解决方案1】:

查看googlei18n/libaddressinput: Google’s postal address library, powering Android and Chromium。项目中有两个模块:android和:common。您应该只需要 :common 来格式化显示区域设置的地址。

import android.location.Address;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.google.i18n.addressinput.common.AddressData;
import com.google.i18n.addressinput.common.FormOptions;
import com.google.i18n.addressinput.common.FormatInterpreter;
...
public static String getFormattedAddress(@NonNull final Address address, 
                                         @NonNull final String regionCode) {
    final FormatInterpreter formatInterpreter
            = new FormatInterpreter(new FormOptions().createSnapshot());
    final AddressData addressData = (new AddressData.Builder()
            .setAddress(address.getThoroughfare())
            .setLocality(address.getLocality())
            .setAdminArea(address.getAdminArea())
            .setPostalCode(address.getPostalCode())
            .setCountry(regionCode) // REQUIRED
            .build());
    // Fetch the address lines using getEnvelopeAddress,
    List<String> addressFragments = formatInterpreter.getEnvelopeAddress(addressData);
    // join them, and send them to the thread.
    return TextUtils.join(System.getProperty("line.separator"),
            addressFragments);
}

注意:regionCode 必须是有效的 iso2 国家代码,因为这是格式解释器从中提取地址格式的地方。 (如果您对格式列表感到好奇,请参阅RegionDataConstants。)

设置地址的 2 字母 CLDR 区域代码;看 地址数据#getPostalCountry()。与传递给 builder,区域代码永远不能为空。

示例:美国

801 栗子街
ST。密苏里州路易斯 63101

例如:日本

〒1600023
西新宿
3-2-11 西新宿 东京新宿区

【讨论】:

  • 一直在找这种库,非常感谢解答!
【解决方案2】:

我在其他平台上做了一些本地化。以下是 Android 本地化指南:http://developer.android.com/guide/topics/resources/localization.html#using-framework

一种方法是使用本地化资源来存储与所需的每个语言环境的地址布局相对应的 MessageFormat 字符串。从那里,您需要参考全球地址块标准,并为您需要的每个语言环境创建格式字符串。

【讨论】:

  • 谢谢,我指的是具有地址 API 的相同 android 本地化,但没有根据所选语言环境提供地址格式。
  • 我认为原因是一个已经输入的邮政地址“属于”一个语言环境并且有固定的格式化方式。例如,按照德国惯例或其他方式表达美国邮政地址没有多大意义。如果您正在访问 ContactsContract 数据库,则只需使用 StructuredPostal 实体的格式化地址字段。
  • 在这个Google example code 中,他们使用类似于我的建议的想法来格式化地址行。不确定是否有更简单的方法。
猜你喜欢
  • 2011-11-25
  • 2018-06-25
  • 2019-08-10
  • 1970-01-01
  • 2014-03-16
  • 2017-01-15
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
相关资源
最近更新 更多