最近一个项目中用到了多语言,可是在有些语言切换失效,挣扎许久终于找到问题了。
这是切换语言的代码:
public void changeAppLanguage(String key) {
Configuration configurat = getResources().getConfiguration();
if (getString(R.string.simplified_Chinese).equals(key)){
configurat.locale = Locale.SIMPLIFIED_CHINESE;
}else if (getString(R.string.traditional_Chinese).equals(key)){
configurat.locale = Locale.TRADITIONAL_CHINESE;
}else if (getString(R.string.English).equals(key)){
configurat.locale = Locale.ENGLISH;
} else {
Configuration config = getResources().getConfiguration();//获取系统的配置
getResources().updateConfiguration(config, getResources().getDisplayMetrics());//跟随系统语言
return;
}
DisplayMetrics metrics = getResources().getDisplayMetrics();
getResources().updateConfiguration(configurat, metrics);
}
文件夹的范围必须大于等于代码中的Locale的范围,解释看下方示例:
例如:字体为英文
1、文件夹为value-en,代码为Locale.ENGLISH或Locale.US(美国),Locale.CANADA(澳大利亚)……
2、文件夹为value-en-rUS,那么代码只能为Locale.US
如果文件夹的范文小于代码中的Locale的范围,那么程序调用的是默认value文件夹下的strings.xml。问题来了,如果删掉默认的strings.xml,那么调用的是哪个文件呢?答案是No,默认文件删掉程序会崩掉。
还有一个小小问题:
右边如果需要选择Any Region之外的语言,选中后直接Enter或者不要碰到图中区域然后点击OK,如果碰到图中区域,选择会跳转到Any Region。