【问题标题】:Force Android DateUtils.getRelativeDateTimeString() to ignore the device locale?强制 Android DateUtils.getRelativeDateTimeString() 忽略设备区域设置?
【发布时间】:2011-09-26 05:18:22
【问题描述】:

我发现使用 android.text.format.DateUtils 相关 API 可以返回像“昨天”或“2 小时前”这样的值非常好 - 但我的应用程序不支持 Android 支持的所有语言。所以,我默认使用英语,但对于我不支持的每种语言,相关字符串都会显示在设备的设置中。

例如:

Last attempt: hace 11 minutos.

对于我不支持的任何语言,我想让 API 调用默认为英语。但是,我看不到任何地方可以为 API 调用设置语言环境——我希望我只是在某个地方错过了它。

有没有办法只为 API 调用设置区域设置,而忽略设备设置?

【问题讨论】:

    标签: android date time locale relative-date


    【解决方案1】:

    这对我的 Android 7 有效

      void forceLocale(Locale locale) {
        Configuration conf = getBaseContext().getResources().getConfiguration();
        updateConfiguration(conf, locale);
        getBaseContext().getResources().updateConfiguration(conf, getResources().getDisplayMetrics());
    
        Configuration systemConf = Resources.getSystem().getConfiguration();
        updateConfiguration(systemConf, locale);
        Resources.getSystem().updateConfiguration(conf, getResources().getDisplayMetrics());
    
        Locale.setDefault(locale);
      }
    
      void updateConfiguration(Configuration conf, Locale locale) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
          conf.setLocale(locale);
        }else {
          //noinspection deprecation
          conf.locale = locale;
        }
      }
    

    【讨论】:

    • 适用于 Android 4.1.2
    • 适用于 Android 5.0
    • 谢谢你为 Android 7.0 工作,但它在 Android 8.0 上不起作用,知道如何让它在 Oreo 上工作
    【解决方案2】:

    根据DateUtils 类的源代码,它使用Resource.getSystem() 和Locale.getDefault() 方法来格式化日期和时间。您可以使用Locale.setDefault() 方法更改默认的Locale,但我认为无法更改Resource.getSystem() 方法的返回值。您可以尝试将默认语言环境更改为Locale.US,但在我看来,在这种情况下结果会更糟。

    【讨论】:

    • 感谢@Pixie 调查它。我拉下源并自己戳了一下,不得不同意。
    • 有人找到解决这个问题的方法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多