使用Locale类来进行存储language和country。
public Locale(String language, String country) {
this(language, country, "");
}
将构建出来的Locale存入到资源中,并重新拿到一个新的Context。
public static Context updateResources(Context context, Locale locale) {
Locale.setDefault(locale);
Resources res = context.getResources();
Configuration config = new Configuration(res.getConfiguration());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
config.setLocale(locale);
final LocaleList localeList = new LocaleList(locale);
LocaleList.setDefault(localeList);
config.setLocales(localeList);
} else {
config.setLocale(locale);
}
// 2
res.updateConfiguration(config, res.getDisplayMetrics());
config.setLayoutDirection(locale);
if (config.fontScale != 1.0f) {
config.fontScale = 1.0f;
}
return context.createConfigurationContext(config);
}
注意2 一定要触发这个代码 否则更新会失败,之前公司的代码只有当Android OS 版本小于 N 的时候会调用这个方法,发现有问题。所以无论什么版本,都要触发一下,参考这篇文章写的很清楚。