注意如果您的最低 API 为 17+,请直接进入此答案的底部。否则,请继续阅读...
注意如果您使用的是 App Bundle,则需要确保禁用语言拆分或动态安装不同的语言。请参阅https://stackoverflow.com/a/51054393。如果您不这样做,它将始终使用回退。
如果你有不同地区的各种 res 文件夹,你可以这样做:
Configuration conf = getResources().getConfiguration();
conf.locale = new Locale("pl");
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Resources resources = new Resources(getAssets(), metrics, conf);
String str = resources.getString(id);
或者,您可以使用@jyotiprakash 指向的方法重新启动您的活动。
注意 像这样调用Resources 构造函数会改变Android 内部的某些内容。您必须使用原始语言环境调用构造函数才能恢复原样。
编辑从特定语言环境中检索资源的一个稍微不同(而且更简洁)的方法是:
Resources res = getResources();
Configuration conf = res.getConfiguration();
Locale savedLocale = conf.locale;
conf.locale = desiredLocale; // whatever you want here
res.updateConfiguration(conf, null); // second arg null means don't change
// retrieve resources from desired locale
String str = res.getString(id);
// restore original locale
conf.locale = savedLocale;
res.updateConfiguration(conf, null);
从 API 级别 17 开始,您应该使用 conf.setLocale() 而不是直接设置 conf.locale。如果您碰巧在从右到左和从左到右的语言环境之间切换,这将正确更新配置的布局方向。 (布局方向在17中介绍过。)
创建一个新的Configuration 对象是没有意义的(正如@Nulano 在评论中建议的那样),因为调用updateConfiguration 会改变调用res.getConfiguration() 获得的原始配置。
如果您要为一个语言环境加载多个字符串资源,我会犹豫将其捆绑到 getString(int id, String locale) 方法中。更改语言环境(使用任一配方)需要框架做大量工作来重新绑定所有资源。最好更新一次语言环境,检索您需要的所有内容,然后重新设置语言环境。
编辑(感谢@Mygod):
如果您的最低 API 级别为 17+,则有更好的方法,如另一个线程上的 this answer 所示。例如,您可以创建多个 Resource 对象,为您需要的每个区域设置一个对象:
@NonNull Resources getLocalizedResources(Context context, Locale desiredLocale) {
Configuration conf = context.getResources().getConfiguration();
conf = new Configuration(conf);
conf.setLocale(desiredLocale);
Context localizedContext = context.createConfigurationContext(conf);
return localizedContext.getResources();
}
然后只需从该方法返回的本地化Resource 对象中检索您喜欢的资源。检索资源后无需重置任何内容。