Search code examples
androidarraysandroid-studiolanguage-translationstring.xml

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


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.


Solution

  • 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();
    }