在activity 或 继承自基类activity 重写以下方法:
@Override
protected void attachBaseContext(Context context) {
LogTools.i(TAG,"attachBaseContext");
String lang=SharedPreferencesUtils.getString(MyApplication.mApplication,Constants.LANGUAGE_KEY,"");
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
LogTools.i(TAG,"7.0===="+lang);
if(lang.length()>0){
Resources resources = context.getResources();
String[] lc=lang.split("_");
Locale locale = new Locale(lc[0], lc[1]);
Configuration configuration = resources.getConfiguration();
configuration.setLocale(locale);
super.attachBaseContext(context.createConfigurationContext(configuration));
}else{
super.attachBaseContext(context);
}
}else{
LogTools.i(TAG,"7.0之前="+lang);
if(lang.length()>0) {
//存储当前语言代码
String[] lc = lang.split("_");
Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.setLocale(new Locale(lc[0], lc[1]));
//更新配置
res.updateConfiguration(conf, dm);
}
super.attachBaseContext(context);
}
}
点击切换 方法:
public void changeAppLanguage() {
// "zh_CN"/"en_US" 语言代码存入本地
SharedPreferencesUtils.setString(context,Constants.LANGUAGE_KEY,"en_US");
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
LogTools.i(TAG,"changeAppLanguage");
}
顺便提个布局建议:阿拉伯语言 切换时 布局错乱问题,在根布局下加入一行代码:
android:layoutDirection="ltr"