如果Android应用需要做本地化,都要用到多语言来适配,例如手机设置成英文后,App内文字变成英文。
App提供资源可以参考官方文档https://developer.android.com/guide/topics/resources/providing-resources#AlternativeResources,App提供各种适配的资源,包括但不限定于:语言和区域,屏幕尺寸,屏幕像素密度。做多语言功能,提供values资源即可。例如中文:values-zh;中文简体:values-zh-rCH;中文繁体:values-zh-rTW;App查找资源可以参考文档https://developer.android.com/guide/topics/resources/providing-resources#BestMatch,而对于语言的资源匹配可以参考这个https://developer.android.com/guide/topics/resources/multilingual-support,7.0之前和之后有些许区别。
这样设置基本实现了多语言,但是如果需要App内切换语言的功能的话需要设计应用内切换语言的代码。主要代码是更新Application和Activity的Resources的语言设置,在Application中的onCreate中更新Resources,在Activity中则需要在attachBaseContext中进行操作,在7.0之后有些许变化,
7.0之前只更新Resources即可,代码如下
private void setConfiguration(Context context) {
Resources resources = context.getResources();
Locale targetLocale = getLocale();
Configuration configuration = resources.getConfiguration();
configuration.locale = targetLocale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());//语言更换生效的代码!
}
7.0之后需要使用createConfigurationContext新建一个Context返回,代码如下
private Context updateResources(Context context) {
Resources resources = context.getResources();
Locale locale = getLocale();
Configuration configuration = resources.getConfiguration();
configuration.setLocale(locale);
return context.createConfigurationContext(configuration);
}
getLocale就是获取当前选择的语言。如果是跟随系统则需要获取系统设置的语言,代码如下
private static Locale getSystemLocale() {
Locale locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //7.0有多语言设置获取顶部的语言
locale = Resources.getSystem().getConfiguration().getLocales().get(0);
} else {
locale = Resources.getSystem().getConfiguration().locale;
}
return locale;
}
每次选择后需要重建Activity,并更新Application的Resources,这时可以选择重建所有的Activity,或者返回MainActivity,只重建MainActivity。
另外:如果在项目中配置了resConfigs,则需要添加自己多语言的配置,例如resConfigs("zh-rCN","zh-rTW","en")