Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get string from different locales in Android?

So I want to get the value of a String in several locales regardless of the current locale setting of the device/app. How should I do that?

Basically what I need is a function getString(int id, String locale) rather than getString(int id)

How could I do that?

Thanks

like image 574
cheng yang Avatar asked Feb 28 '12 02:02

cheng yang


People also ask

How do I localize a string in Android?

Localizing Strings In order to localize the strings used in your application , make a new folder under res with name of values-local where local would be the replaced with the region. Once that folder is made, copy the strings. xmlfrom default folder to the folder you have created. And change its contents.

How do I change localization in Android?

You'll find this screen either in the System Settings app: Languages, or System Settings: System: Languages and input. The Language preference screen should contain one entry called “English (Europe)”. Click Add language and add a fallback language.

In which folder can you find the string resource file strings XML?

The XML resource files containing localized strings are placed in subfolders of the project's res folder.


3 Answers

NOTE If your minimum API is 17+, go straight to the bottom of this answer. Otherwise, read on...

NOTE If you are using App Bundles, you need to make sure you either disable language splitting or install the different language dynamically. See https://stackoverflow.com/a/51054393 for this. If you don't do this, it will always use the fallback.

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

Alternatively, you can just restart your activity using the method pointed to by @jyotiprakash.

NOTE Calling the Resources constructor like this changes something internally in Android. You will have to invoke the constructor with your original locale to get things back the way they were.

EDIT A slightly different (and somewhat cleaner) recipe for retrieving resources from a specific locale is:

Resources res = getResources();
Configuration conf = res.getConfiguration();
Locale savedLocale = conf.locale;
conf.locale = desiredLocale; // whatever you want here
res.updateConfiguration(conf, null); // second arg null means don't change

// retrieve resources from desired locale
String str = res.getString(id);

// restore original locale
conf.locale = savedLocale;
res.updateConfiguration(conf, null);

As of API level 17, you should use conf.setLocale() instead of directly setting conf.locale. This will correctly update the configuration's layout direction if you happen to be switching between right-to-left and left-to-right locales. (Layout direction was introduced in 17.)

There's no point in creating a new Configuration object (as @Nulano suggests in a comment) because calling updateConfiguration is going to change the original configuration obtained by calling res.getConfiguration().

I would hesitate to bundle this up into a getString(int id, String locale) method if you're going to be loading several string resources for a locale. Changing locales (using either recipe) calls for the framework to do a lot of work rebinding all the resources. It's much better to update locales once, retrieve everything you need, and then set the locale back.

EDIT (Thanks to @Mygod):

If your minimum API level is 17+, there's a much better approach, as shown in this answer on another thread. For instance, you can create multiple Resource objects, one for each locale you need, with:

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

Then just retrieve the resources you like from the localized Resource object returned by this method. There's no need to reset anything once you've retrieved the resources.

like image 127
Ted Hopp Avatar answered Oct 10 '22 03:10

Ted Hopp


Here is a combined version of the approaches described by Ted Hopp. This way, the code works for any Android version:

public static String getLocaleStringResource(Locale requestedLocale, int resourceId, Context context) {
    String result;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // use latest api
        Configuration config = new Configuration(context.getResources().getConfiguration());
        config.setLocale(requestedLocale);
        result = context.createConfigurationContext(config).getText(resourceId).toString();
    }
    else { // support older android versions
        Resources resources = context.getResources();
        Configuration conf = resources.getConfiguration();
        Locale savedLocale = conf.locale;
        conf.locale = requestedLocale;
        resources.updateConfiguration(conf, null);

        // retrieve resources from desired locale
        result = resources.getString(resourceId);

        // restore original locale
        conf.locale = savedLocale;
        resources.updateConfiguration(conf, null);
    }

    return result;
}

Usage example:

String englishName = getLocaleStringResource(new Locale("en"), R.string.name, context);

Note

As already stated in the original answer, it might be more efficient to replace multiple call of the above code with a single configuration change and multiple resources.getString() calls.

like image 35
Johnson_145 Avatar answered Oct 10 '22 03:10

Johnson_145


Based on the above answers which awesome but a little complex. try this simple function:

public String getResStringLanguage(int id, String lang){
    //Get default locale to back it
    Resources res = getResources();
    Configuration conf = res.getConfiguration();
    Locale savedLocale = conf.locale;
    //Retrieve resources from desired locale
    Configuration confAr = getResources().getConfiguration();
    confAr.locale = new Locale(lang);
    DisplayMetrics metrics = new DisplayMetrics();
    Resources resources = new Resources(getAssets(), metrics, confAr);
    //Get string which you want
    String string = resources.getString(id);
    //Restore default locale
    conf.locale = savedLocale;
    res.updateConfiguration(conf, null);
    //return the string that you want
    return string;
}

Then simply call it: String str = getResStringLanguage(R.string.any_string, "en");

Happy code :)

like image 5
Amr Jyniat Avatar answered Oct 10 '22 04:10

Amr Jyniat