Can I access to resources from different locale android?
Asked Answered
A

4

12

I have two locale in my application. Can I access to resources, for example string array from different locale without to change current locale ? I mean with coding I don't like to change it in Settings.

Aerostatics answered 3/6, 2012 at 22:52 Comment(0)
A
36

The better solution would be (if you're on API 17):

@NonNull
protected String getEnglishString() {
    Configuration configuration = getEnglishConfiguration();

    return getContext().createConfigurationContext(configuration).getResources().getString(message);
}

@NonNull
private Configuration getEnglishConfiguration() {
    Configuration configuration = new Configuration(getContext().getResources().getConfiguration());
    configuration.setLocale(new Locale("en"));
    return configuration;
}
Animalist answered 10/11, 2015 at 11:41 Comment(3)
Great answer, thank you. Wish I could back-port this and save myself the effort of messing with the AssetManagerOverblouse
Thanks! This is also the solution recommended by Google: code.google.com/p/android/issues/detail?id=67672Anselm
Thank you Eugen.. This answer should be marked as correct one.Gulgee
A
9

Here is the code that work for me if cMK is String array from current locale and cEN is string array from diffrent locale

 cMK = getResources().getStringArray(R.array.cities);

         Configuration confTmp =new Configuration( getResources().getConfiguration());

         confTmp.locale = new Locale("en");

         DisplayMetrics metrics = new DisplayMetrics();

         getWindowManager().getDefaultDisplay().getMetrics(metrics);

         Resources resources = new Resources(getAssets(), metrics, confTmp);

         /* get localized string */
         cENG = getResources().getStringArray(R.array.cities);

The current locale isn't changed and that was the point.

Aerostatics answered 4/6, 2012 at 9:35 Comment(4)
did you mean: "cENG = resources.getStringArray(R.array.cities);" ?Julissajulita
It changes locale for context (for your activity for example)Animalist
Constructor of Resources changes the locale of your app, so be careful restoring the original resource.Marchak
See the comments under the answer of #5245389 on how to fix thisMagellan
H
2

Yes, you can. You have to create a new Resources object specifying the intending Configuration.

Reference: http://developer.android.com/reference/android/content/res/Resources.html#Resources%28android.content.res.AssetManager,%20android.util.DisplayMetrics,%20android.content.res.Configuration%29

Holman answered 3/6, 2012 at 22:54 Comment(0)
D
0

In Java 7 (so not android) Locale can be set differently for format resources and different for display:

Locale.setDefault(DISPLAY, Locale.PL);
Locale.setDefault(FORMAT, Locale.US);

Similar thread: Changing Locale within the app itself .

Dornick answered 30/1, 2013 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.