切换系统语言分为下面两个步骤:
1. 创建不同语言资源;
2. 替换当前页面 Context 所持有的资源;
一、创建不同语言资源
创建步骤如下:
创建资源1.png 创建资源2.png 创建资源3.png 创建资源4.png二、替换资源
- 界面需要重新创建,使用 recreate(); 或者 重新打开界面。
- 在 attachBaseContext(Context) 方法中替换Context的资源。
//可以在 BaseActivity 中使用
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(Utils.attachBaseContext(newBase));
}
- 切换配置
public static Context attachBaseContext(Context context) {
//不同版本设置方式不一样
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return createResources(context);
} else {
updateResources(context);
return context;
}
}
@TargetApi(Build.VERSION_CODES.N)
private static Context createResources(Context context) {
Resources resources = context.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
Configuration configuration = resources.getConfiguration();
//获取语言设置,一般用户设置的语言优先级更高,如果用户没有设置,则获取系统语言
Locale targetLocale = getLocale(context);
configuration.setLocale(targetLocale);
resources.updateConfiguration(configuration, dm);
//创建配置
return context.createConfigurationContext(configuration);
}
public static void updateResources(Context pContext) {
Locale targetLocale = getLocale(pContext);
Configuration configuration = pContext.getResources().getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLocale(targetLocale);
} else {
configuration.locale = targetLocale;
}
Resources resources = pContext.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
//更新配置
resources.updateConfiguration(configuration, dm);
}
- 获取系统语言
public static Locale getSystemLocale(Context context) {
Locale locale;
//7.0有多语言设置获取顶部的语言
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
locale = LocaleList.getDefault().get(0);
} else {
locale = context.getResources().getConfiguration().locale;
}
return locale;
}
注意:
不能使用 Application 的 Context 来获取文字资源,必须使用 Activity 的 Context;
网友评论