Android app内语言环境切换 附Demo
app内语言的切换是现在比较常见的功能,确实方便用户进行语言间的切换。先说一下整体思路,用户在做语言切换操作时做Configuration配置处理,当前操作页面recreate。将用户选择语言通过sp记录在本地,7.0之前系统直接改变Configuration的local属性就可以做到语言切换,7.0以后需要在页面的attachBaseContext方法做createConfigurationContext处理。
上图先
Configuration类
语言切换,主要是Configuration类的配置。通过设置Configuration 的 locale 属性来切换语言环境。local包含语言、国家等信息。
需要注意的是。7.0版本以后的语言是一个列表:
Google把语言这一块进行了较大的调整,系统会根据这个列表的优先级去适配语言。所以7.0以后的语言配置有所改变:
Configuration环境配置
Context context = UIUtils.getContext().getApplicationContext();
Configuration configuration = context.getResources().getConfiguration();
//7.0以后
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
configuration.setLocale(userLocale);
} else {
configuration.locale = userLocale;
}
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
context.getResources().updateConfiguration(configuration, displayMetrics);
saveUserLocale(userLocale);
7.0后需要在activity的attachBaseContext中进行处理,一般是在baseActivity中操作
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(LanguageUtil.attachBaseContext(newBase));
}
@TargetApi(Build.VERSION_CODES.N)
public static Context updateResources(Context context) {
Resources resources = context.getResources();
Locale locale = getUserLocale();// getSetLocale方法是获取新设置的语言
Configuration configuration = resources.getConfiguration();
configuration.setLocale(locale);
configuration.setLocales(new LocaleList(locale));
return context.createConfigurationContext(configuration);
}
补充一点:
如果有资源文件是代码中动态获取的,7.0以上getResources也是要更新Configuration操作的,不然刚刚切换是拿不到正确的语言环境下资源的
/**
* 获取资源
*/
public static Resources getResources() {
Resources resources = getContext().getResources();
Configuration config = resources.getConfiguration();
DisplayMetrics dm = resources.getDisplayMetrics();// 获得屏幕参数:主要是分辨率,像素等。
config.locale = LanguageUtil.getUserLocale();
resources.updateConfiguration(config, dm);
return resources;
}