1、问题原因:
在Android7(N)之前WebView的渲染是通过Android System webView来实现的。但是在Android7(N)之后WebView会被作为一个应用程序的方式服务于各个三方APP。由于WebView这里是作为一个单独的应用程序,所以他不会被绑定到你自己APP设置的Local上。不仅如此,WebView还会把语言变成设备的Local设置。然后相应的资源文件也会被变成设备语言下的资源文件。这样就导致了只要打开了含有WebView的页面,应用内语言设置就失效的问题。
2、解决方案:
(1)第1步,在所有Activity下重设语言。StackOverFlow的回答中说也可以只在含有WebView的Activity中重设。但是各位,为了保证不给自己挖坑,还是全设置掉好一点。在你的BaseActivity中,并且在调用setContentView之前调用如下代码设置你的Local:
public static void setLocale(Locale locale){
Locale.setDefault(locale);
Context context = MusafirApplication.getInstance();
final Resources resources = context.getResources();
final Configuration config = resources.getConfiguration();
config.setLocale(locale);
context.getResources().updateConfiguration(config,
resources.getDisplayMetrics());
}
(2)第2步:在你的Application的onCreate方法中以及用户可能正在改变语言的地方添加如下代码():
new WebView(this).destroy();
这样之后,问题解决。
(3)修改语言的代码(在BaseActivity中调用该方法)
public static void switchLanguage( String language) { //设置应用语言类型 Resources resources = MyApplication.getContext().getResources(); Configuration config = resources.getConfiguration(); DisplayMetrics dm = resources.getDisplayMetrics(); /** * 适配Android7.0以上系统 */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){ if ("zh".equals(language)) { config.setLocale(Locale.SIMPLIFIED_CHINESE); } else if ("ja".equals(language)){ config.setLocale(Locale.JAPANESE); } else { config.setLocale(Locale.ENGLISH); } }else { if ("zh".equals(language)) { config.locale = Locale.SIMPLIFIED_CHINESE; } else if ("ja".equals(language)){ config.locale = Locale.JAPANESE; } else { config.locale = Locale.ENGLISH; } } resources.updateConfiguration(config, dm); //保存设置语言的类型 LocalData.getInstance().setLanguage(language); }