因此,无论设备/应用程序的当前区域设置如何,我都想在多个区域设置中获取字符串的值。我该怎么做?
基本上我需要的是一个函数 getString(int id, String locale)
而不是 getString(int id)
我该怎么做?
谢谢
最佳答案
注意如果您的最低 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 指向的方法重新启动您的 Activity 。
注意 像这样调用 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()
.
如果您要为一个语言环境加载多个字符串资源,我会犹豫将其 bundle 到一个 getString(int id, String locale)
方法中。更改语言环境(使用任一配方)需要框架做大量工作来重新绑定(bind)所有资源。最好更新一次语言环境,检索您需要的所有内容,然后重新设置语言环境。
编辑(感谢@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
对象中检索您喜欢的资源。检索资源后无需重置任何内容。
关于android - 如何从 Android 中的不同语言环境获取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9475589/