本文共 3381 字,大约阅读时间需要 11 分钟。
public static Context checkLanguage(Context context) { // index:本地保存的语言类型:0英语,1中文简体,2中文繁体 int index = DataRepository.getInstence().getSpValue(SPConstant.SP_LANGUAGE, SPConstant.KEY_LANGUAGE_INDEX, -1); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); DisplayMetrics displayMetrics = resources.getDisplayMetrics(); Locale locale; if (index == LanguageConstant.ENGLISH) { locale = Locale.ENGLISH; } else if (index == LanguageConstant.SIMPLIFIED_CHINESE) { locale = Locale.SIMPLIFIED_CHINESE; } else if (index == LanguageConstant.CHINESE_TW) { locale = Locale.TRADITIONAL_CHINESE; } else { // 获取系统默认语言,版本兼容 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { locale = LocaleList.getDefault().get(0); } else { locale = Locale.getDefault(); } } // 设置语言,版本做兼容 // 这个updateConfiguration方法已废弃,官方建议用createConfigurationContext。但是仍然可以用 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLocale(locale); context = context.createConfigurationContext(configuration); } else { configuration.locale = locale; resources.updateConfiguration(configuration, displayMetrics); } return context;}
// 获取系统当前语言if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { locale = LocaleList.getDefault().get(0);} else { locale = Locale.getDefault();}// 设置应用语言;更新配置信息if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLocale(locale); context = context.createConfigurationContext(configuration);} else { configuration.locale = locale; resources.updateConfiguration(configuration, displayMetrics);}
@Override protected void attachBaseContext(Context base) { super.attachBaseContext(checkLanguage(base));}
转载地址:http://ohxsa.baihongyu.com/