UPDATE Jan 2022
New Way:
Set locale using the AndroidX library that will handle the storage itself for uper version of 7.0.0 (API level >24) - PerAppLanguages
March 2021
I used the below code and it worked perfectly on all versions.
Old code:
Note: For 6.0.1 version must update locale before setContentView(R.layout.activity_main)
and for uper version of 7.0.0 (API level >24) need to override protected void attachBaseContext(Context newBase)
in all Activity of your project.
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) {
ContextUtils.updateLocale(MainActivity.this, ContextUtils.getSavedLanguage(MainActivity.this));
}
setContentView(R.layout.activity_main);
......
.....
}
@Override
protected void attachBaseContext(Context newBase) {
String localeToSwitchTo= ContextUtils.getSavedLanguage(newBase);
ContextWrapper localeUpdatedContext = ContextUtils.updateLocale(newBase, localeToSwitchTo);
super.attachBaseContext(localeUpdatedContext);
}
ContextUtils
public class ContextUtils extends ContextWrapper {
public ContextUtils(Context base) {
super(base);
}
public static ContextWrapper updateLocale(Context context, String lang) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
Locale localeToSwitchTo = new Locale(lang);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
configuration.setLocale(localeToSwitchTo);
LocaleList localeList = new LocaleList(localeToSwitchTo);
LocaleList.setDefault(localeList);
configuration.setLocales(localeList);
context = context.createConfigurationContext(configuration);
}else {
Locale.setDefault(localeToSwitchTo);
configuration.locale=localeToSwitchTo;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
}
return new ContextUtils(context);
}
public static String getSavedLanguage(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(
context.getApplicationContext());
return preferences.getString("SETTINGS_LANG", "en");
}
public static void setSavedLanguage(Context context, String lang){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(
context.getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("SETTINGS_LANG", lang);
editor.apply();
}
}