How to change language of app when user selects language? How to change language of app when user selects language? android android

How to change language of app when user selects language?


It's excerpt for the webpage: http://android.programmerguru.com/android-localization-at-runtime/

It's simple to change the language of your app upon user selects it from list of languages. Have a method like below which accepts the locale as String (like 'en' for English, 'hi' for hindi), configure the locale for your App and refresh your current activity to reflect the change in language. The locale you applied will not be changed until you manually change it again.

public void setLocale(String lang) {     Locale myLocale = new Locale(lang);     Resources res = getResources();     DisplayMetrics dm = res.getDisplayMetrics();     Configuration conf = res.getConfiguration();     conf.locale = myLocale;     res.updateConfiguration(conf, dm);     Intent refresh = new Intent(this, AndroidLocalize.class);     finish();    startActivity(refresh); } 

Make sure you imported following packages:

import java.util.Locale; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.util.DisplayMetrics; 

add in manifest to activity android:configChanges="locale|orientation"


Good solutions explained pretty well here. But Here is one more.

Create your own CustomContextWrapper class extending ContextWrapper and use it to change Locale setting for the complete application.Here is a GIST with usage.

And then call the CustomContextWrapper with saved locale identifier e.g. 'hi' for Hindi language in activity lifecycle method attachBaseContext. Usage here:

@Overrideprotected void attachBaseContext(Context newBase) {    // fetch from shared preference also save the same when applying. Default here is en = English    String language = MyPreferenceUtil.getInstance().getString("saved_locale", "en");    super.attachBaseContext(MyContextWrapper.wrap(newBase, language));}


all the above @Uday's code is perfect but only one thing is missing(default config in build.gradle)

public void setLocale(String lang) { Locale myLocale = new Locale(lang); Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); conf.locale = myLocale; res.updateConfiguration(conf, dm); Intent refresh = new Intent(this, AndroidLocalize.class); finish();startActivity(refresh); 

}

Mine was not working just because the languages were not mentioned in the config file(build.gradle)

 defaultConfig {    resConfigs "en", "hi", "kn"}

after that, all languages started running