【问题标题】:How to format an Address for multiline display?如何格式化多行显示的地址?
【发布时间】:2015-10-02 19:41:03
【问题描述】:

类似于 2011 年的 this question,缺乏令人满意的答案:

我正在开发的应用程序将在全球范围内部署。应用程序本身只关心Address 的纬度/经度,但它需要以多行格式向用户显示Address。谷歌的地理编码器提供了一个格式化的地址,但它在一行中,用逗号分隔。将其拆分为多行需要了解在给定国家/地区如何格式化多行地址。例如,在美国,习惯将城市和州放在同一行,用逗号分隔。

考虑到反向地理编码的地址可能不完整,是否有内置方法(或第三方库或 Web 服务)可以格式化来自 Address 的多行地址?

【问题讨论】:

    标签: 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 西新宿 东京新宿区

    【讨论】:

    • 这个库看起来很有趣,但是文档没有说明如何将它安装在我的项目的 build.gradle 中,该库在哪里可用等等。 @Funktional 你能详细说明一下吗?
    • @Sebastien 个人 - 我将项目安装为 git 子模块,然后简单地使用以下命令导入公共库: compile project(':libaddressinput')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2012-05-12
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多