Ad

Localization With Strings.xml

- 1 answer

I want to change the locale within my app. I have several strings.xml file depending on various locales.Issue I am facing is the app locale gets updated but the strings like in title or tabs header doesn't gets updated depending on locale changed.

I have killed my app using System.exit(0) and manually restarted it but changes doesn't gets reflected. Please help.

Locale locale = new Locale(language);
    Locale.setDefault(locale);

    Resources res = context.getResources();
    Configuration config = new Configuration(res.getConfiguration());
    if (Build.VERSION.SDK_INT >= 17) {
        config.setLocale(locale);
        context = context.createConfigurationContext(config);
    } else {
        config.locale = locale;
        res.updateConfiguration(config, res.getDisplayMetrics());
    }

    res.updateConfiguration(config, res.getDisplayMetrics());
Ad

Answer

You can use bellow code to change locale

public void setLocale(Context context, String language)
{
    Locale newLocale;

    switch (language)
    {
        case "UK":
            newLocale = Locale.UK;
            break;

        default:
            newLocale = Locale.US;
            break;
    }

    Locale.setDefault(newLocale);
    Configuration config = new Configuration();

    if (Build.VERSION.SDK_INT >= 17) {
        config.setLocale(newLocale);
    } else {
       config.locale = newLocale;
    }

    context.getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}

Note: You must use this code on create of MainActivity.

To restart your App you can use this:

public void resetApp(Context context) {
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(getBaseContext().
    getPackageName());
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}

Java Supported Locales

Android - Get List of supported Locales

Ad
source: stackoverflow.com
Ad