我已经尝试在API 27上对其进行测试,并且效果很好,但是当我切换到API 21时,它不会更改语言。
private void setLocale(String lang) {
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
//config.locale = locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
config.setLocale(locale);
} else {
config.locale = locale;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
getBaseContext().createConfigurationContext(config);
} else {
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
//getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
SharedPreferences.Editor editor = getSharedPreferences("Settings", MODE_PRIVATE).edit();
editor.putString("My_Lang", lang);
editor.apply();
}
public void loadlocale(){
SharedPreferences prefs = getSharedPreferences("Settings", Activity.MODE_PRIVATE);
String language = prefs.getString("My_Lang", "");
setLocale(language);
}
我在onCreate的setContentView之前调用“ loadlocal()”。
然后在onClickListener中执行
....
setLocale("en");
recreate();
//or
setLocale("ar");
recreate();
....