如何让Android的DateUtils.getRelativeDateTimeString()忽略设备语言环境?

18
我发现使用android.text.format.DateUtils 相关的API返回像“昨天”或“2小时前”这样的值非常好用,但我的应用程序不支持Android支持的每种语言。因此,我默认使用英语,但对于我不支持的每种语言,相对字符串将显示在设备的设置中。
例如,如下所示: Last attempt: hace 11 minutos. 我想使API调用默认为任何我不支持的语言使用英语。然而,我没有看到在API调用中设置Locale的地方-我希望我只是在某个地方忽略了它。
是否有一种方法可以仅对API调用设置区域设置,忽略设备设置?
2个回答

15

在 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。 - Atetc
工作于Android 5.0。 - Son Huy TRAN
1
谢谢 在Android 7.0上工作正常,但在Android 8.0上无法运行,有什么办法可以让它在Oreo上运行? - Andrew Hossam

12

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


感谢@Pixie的关注。我已经下载了源代码并自己查看了一下,必须同意这一点。 - Eric
1
有人解决了这个问题吗? - Lukáš Neoproud

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接