Android studio - 在 string.xml 中获取数组字符串项的翻译
Android studio - get a translation of an array-string's item in string.xml
我有一个应用程序允许用户从 string.xml:
中的数组中选择一个项目
<array-string name="countries">
<item>USA</item>
<item>UK</item>
</array-string>
和 translated-to-Chinese string.xml 中的另一个数组:
<array-string name="countries">
<item>美国</item>
<item>联合王国</item>
</array-string>
比如app有两个TextViews
,我想让用户用中文select某个国家,第一个TextView
用中文显示值,第二个用中文显示它的英文值(默认值 string.xml)。
我希望我的意图很明确。
如果您有针对不同语言环境的各种 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();
}
strings.xml
的翻译版本不用于此目的。
它们用于提供语言环境字符串资源。
由于您需要在相同语言版本的应用程序中同时使用中文和英文值,因此您应该将两个字符串数组放在相同的默认值 strings.xml
中,并为它们提供适当的 ID,例如 countries_chinese
和 countries_english
。
然后将它们加载到 2 个具有适当名称的单独数组中,并使用每个数组的相应值。
我有一个应用程序允许用户从 string.xml:
中的数组中选择一个项目<array-string name="countries">
<item>USA</item>
<item>UK</item>
</array-string>
和 translated-to-Chinese string.xml 中的另一个数组:
<array-string name="countries">
<item>美国</item>
<item>联合王国</item>
</array-string>
比如app有两个TextViews
,我想让用户用中文select某个国家,第一个TextView
用中文显示值,第二个用中文显示它的英文值(默认值 string.xml)。
我希望我的意图很明确。
如果您有针对不同语言环境的各种 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();
}
strings.xml
的翻译版本不用于此目的。
它们用于提供语言环境字符串资源。
由于您需要在相同语言版本的应用程序中同时使用中文和英文值,因此您应该将两个字符串数组放在相同的默认值 strings.xml
中,并为它们提供适当的 ID,例如 countries_chinese
和 countries_english
。
然后将它们加载到 2 个具有适当名称的单独数组中,并使用每个数组的相应值。