18

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

例如,像:

Last attempt: hace 11 minutos.

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

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

4

2 回答 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;
    }
  }
于 2014-11-11T11:55:06.907 回答
12

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

于 2011-07-07T06:23:42.897 回答