Android旋转屏幕后国际化语言失效的解决的方法

本文已同步至个人博客:liyuyu.cn

近期在项目中使用到了国际化多语言(英文+中文),但在使用时发现了一个问题。当屏幕旋转后。APP语言(中文)自己主动转换为了系统语言(英文)。设置了Activity的android:configChanges="orientation|screenSize"属性也无效。于是求助Stackoverflow,你懂的,最后问题攻克了。于是整理了此文以作參考。

1.新建FunctionApplication类继承Application。覆写onConfigurationChanged。代码例如以下:

public class FunctionApplication extends Application{
 
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
        toChinese();
    }
 
    public void toChinese()
    {
        String languageToLoad  = "zh"; 
        Locale locale = new Locale(languageToLoad);  
        Locale.setDefault(locale);  
        Configuration config = getResources().getConfiguration();  
        DisplayMetrics metrics = getResources().getDisplayMetrics();  
        config.locale = Locale.SIMPLIFIED_CHINESE;  
        getResources().updateConfiguration(config, metrics); 
    }
}
2.改动AndroidManifest.xml文件。application节点指定为我们自己定义的FunctionApplication

 <application
        android:name="com.xxx.xxxx.FunctionApplication"
        android:allowBackup="true"
        android:configChanges="orientation|screenSize|locale"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
至此。旋转屏幕后语言失效的问题就可攻克了。

查阅了相关资料。发如今屏幕旋转时触发onConfigurationChanged(Configuration newConfig)方法时。这个newConfig取的是系统的,这就是为什么语言会切换到系统语言的原因。所以在这里我们再次设定下locale就能够了。


原文地址:https://www.cnblogs.com/yfceshi/p/7026848.html