我发现使用返回值(如"昨天"或"2小时前"(的android.text.format.DateUtils
相关API非常好,但我的应用程序并不支持Android的所有语言。因此,我默认为英语,但对于我不支持的每种语言,相对字符串都会显示在设备的设置中。
例如:
Last attempt: hace 11 minutos.
对于我不支持的任何语言,我想将API调用默认为英语。然而,我看不到任何地方可以为API调用设置Locale——我希望我只是在某个地方错过了它。
有没有办法只为API调用设置区域设置,而忽略设备设置?
这适用于我的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;
}
}
根据DateUtils
类的源代码,它使用Resource.getSystem()
和Locale.getDefault()
方法来格式化日期和时间。您可以使用Locale.setDefault()
方法更改默认的Locale
,但我认为不可能更改Resource.getSystem()
方法的返回值。您可以尝试将默认区域设置更改为Locale.US
,但在我看来,在这种情况下,结果会更糟。