You can extend Application class (you have to declare it in the manifest as well) and put something like this in it.
Whenever you want to change language you can then call
((App)getApplicationContext()).changeLang(lang);
from within your activity.
R.string.locale_lang is just a key which is stored in strings.xml for shared preferences
public class App extends Application {
private Locale locale = null;
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (locale != null) {
Locale.setDefault(locale);
Configuration config = new Configuration(newConfig);
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
}
@Override
public void onCreate() {
super.onCreate();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String lang = settings.getString(getString(R.string.locale_lang), "");
changeLang(lang);
}
public void changeLang(String lang) {
Configuration config = getBaseContext().getResources().getConfiguration();
if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {
Editor ed = PreferenceManager.getDefaultSharedPreferences(this).edit();
ed.putString(getString(R.string.locale_lang), lang);
ed.commit();
locale = new Locale(lang);
Locale.setDefault(locale);
Configuration conf = new Configuration(config);
conf.locale = locale;
getBaseContext().getResources().updateConfiguration(conf, getBaseContext().getResources().getDisplayMetrics());
}
}
public String getLang(){
return PreferenceManager.getDefaultSharedPreferences(this).getString(this.getString(R.string.locale_lang), "");
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…