1

我有一个应用程序,让用户有权从string.xml的数组中选择一个项目:

<array-string name="countries">
    <item>USA</item>
    <item>UK</item>
</array-string>

以及翻译成中文的 string.xml中的另一个数组:

<array-string name="countries">
    <item>美国</item>
    <item>联合王国</item>
</array-string>

例如,应用程序有两个TextViews,我希望用户用中文选择某个国家,第一个TextView显示中文值,第二个显示英文值(来自默认 string.xml)。

我希望我的意图很明确。

4

2 回答 2

1

的翻译版本strings.xml不用于此目的。
它们用于提供区域语言字符串资源。
由于您在应用程序的同一语言版本中需要中文和英文值,因此您应该将两个字符串数组置于相同的默认值中strings.xml,并为它们提供适当的 id,例如countries_chinesecountries_english
然后将它们加载到 2 个具有正确名称的单独数组中,并使用每个数组的相应值。

于 2018-08-27T22:59:38.400 回答
1

如果您有用于不同语言环境的各种 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);

如果你的 min sdk > 17 试试这个

@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();
}
于 2018-08-27T22:50:05.230 回答