Android studio - get a translation of an array-string's item in string.xml

2.2k Views Asked by At

I have an application that gives the user the right to choose an item from array in string.xml:

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

and another array in the translated-to-Chinese string.xml:

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

For example, the app has two TextViews, I want the user to select a certain country in Chinese, the first TextView shows the value in Chinese & the second shows its value in English (from default string.xml).

I hope my intent is clear.

2

There are 2 best solutions below

2
On BEST ANSWER

If you have various res folders for different locales, you can do something like this:

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);

If your min sdk > 17 try this

@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();
}
2
On

Translated versions of strings.xml are not used for this purpose.
They are used to provide locale-language string resources.
Since you need in the same language version of your app both the Chinese and the English values you should have put both the string-arrays in the same default strings.xml and give them proper ids like countries_chinese and countries_english.
Then load them in 2 separate arrays with proper names and use the corresponding values of each.