7

I have a setting in my app that allows users to select different localization (languages), ie Chinese, German, etc.

What I would like to do is that once the user makes their choice, to immediately update the layout with strings in the currently selected language. Of course, I want the lang change propagated to ALL current activities, without reloading the app.

I found this (haven't tried it yet) but was wondering if there is a cleaner way of doing it.

https://web.archive.org/web/20210127121431/http://www.tutorialforandroid.com/2009/01/force-localize-application-on-android.html

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Saideira
  • 2,374
  • 6
  • 38
  • 49

2 Answers2

2

I also had this issue.I used the code below and then it changed the language without refreshing the activity

public void setLocale(String lang) {

    myLocale = new Locale(lang);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
    onConfigurationChanged(conf);
    /*Intent refresh = new Intent(this, AndroidLocalize.class);
    startActivity(refresh);*/
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
  // refresh your views here
    lblLang.setText(R.string.langselection);
  super.onConfigurationChanged(newConfig);
}

I hope it would help you.......

Milan Shukla
  • 1,602
  • 18
  • 16
  • 1
    Copied from most voted answer on the following link. Even the commented code. http://stackoverflow.com/questions/12908289/how-change-language-of-app-on-user-select-language – Leo supports Monica Cellio Jun 24 '15 at 00:48
0

There are some steps that you should implement

First, you need to change the locale of your configuration

    Resources resources = context.getResources();

    Configuration configuration = resources.getConfiguration();
    configuration.locale = new Locale(language);

    resources.updateConfiguration(configuration, resources.getDisplayMetrics());

Second, if you want your changes to apply directly to the layout that is visible, you either can update the views directly or you can just call activity.recreate() to restart the current activity.

And also you have to persist your changes because after user closes your application then you would lose the language change.

I explained more detailed solution on my blog post Change Language Programmatically in Android

Basically, you just call LocaleHelper.onCreate() on your application class and if you want to change locale on the fly you can call LocaleHelper.setLocale()

Gunhan
  • 6,807
  • 3
  • 43
  • 37