Reputation: 315
I'm trying to change the language of my app.
I implement this code :
public static void setLocale(Resources res, String lang) {
Configuration conf = new Configuration(res.getConfiguration());
switch (lang) {
case "French" :
conf.locale = new Locale("fr");
break;
case "Dutch" :
conf.locale = new Locale("nl");
break;
case "English" :
conf.locale = new Locale("en");
break;
}
res.updateConfiguration(conf, res.getDisplayMetrics());
}
And after that I refresh my activity using this code :
Intent refresh = new Intent(getActivity(), HomeActivity.class);
getActivity().finish();
startActivity(refresh);
This code works, but when I close the app (remove from background) and reopen it, the language return to the default language of my device.
Is there any way to keep the selected language when I reopen my app ?
Upvotes: 1
Views: 574
Reputation: 4661
I am using this in my application, its working fine,Give a try hope it will help you
public static void changeLanguageSettings(Context context,String language){
try{
Locale mLocale = new Locale(language);
Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration configuration = res.getConfiguration();
Configuration newConfig = new Configuration(configuration);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
newConfig.setLocale(mLocale);
}else{
newConfig.locale = mLocale;
}
context.getResources().updateConfiguration(newConfig, dm);
}catch(Exception e){
e.printStackTrace();
}
}
Upvotes: 0
Reputation: 799
you can store in default shared Preference:
PreferenceManager.getDefaultSharedPreferences().edit().putString("Locale", localVal).commit();
and than every time the app start retrive it by:
locale = PreferenceManager.getDefaultSharedPreferences().getString("Locale", "defaultValue");
Upvotes: 2