Changing locale: Force activity to reload resources?

So I have a language setting in my application. When the language is switched, I would like all the textviews etc to change language immediately. Currently I just change the locale in the configuration, so the language has changed when the user restarts the activity.

An ugly solution to my problem would be to make each textview load the new resources each time the language is changed. Is there a better solution? Perhaps a neat way to discretely restart the activity? Or maybe just force reload of the resources?


In your AndroidManifest.xml, add this attribute to your Activity

android:configChanges="locale"

In your activity override onConfigurationChanged()

@Override
public void onConfigurationChanged(Configuration newConfig) {
  // refresh your views here
  super.onConfigurationChanged(newConfig);
}

https://developer.android.com/guide/topics/manifest/activity-element.html#config


I think the question is switching language in runtime for the app and displaying localized messages in UI. android:configChanges="locale" calls onConfigurationChanged if the system locale is changed (in setting of your device) while the app is running, and not if you change locale in the code for your app, which I guess is what you want to accomplish. That's why it's not refreshing.


Here is the method I use during every activity onCreate() or onResume() depending on my needs (if my activity will be resuming after user changed language settings or will always be created with language already set):

From there I just refresh the view manually or from onConfigurationChanged() which get called after this method finishes.

public static void changeLocale(Activity activity, String language)
{
    final Resources res = activity.getResources();
    final Configuration conf = res.getConfiguration();
    if (language == null || language.length() == 0)
    {
        conf.locale = Locale.getDefault();
    }
    else
    {
        final int idx = language.indexOf('-');
        if (idx != -1)
        {
            final String[] split = language.split("-");
            conf.locale = new Locale(split[0], split[1].substring(1));
        }
        else
        {
            conf.locale = new Locale(language);
        }
    }

    res.updateConfiguration(conf, null);
}