Android应用内部实现多语言,一键切换语言,国际化适配

1.首先提供多语言对应的string值  如en对应英语, fr对应法语

 两个文件中包含同样的key, 对应不同的语言的value

2.java代码相应用户切换语言动作

 private static void setAppLanguage(Context context, Locale locale) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        Configuration configuration = resources.getConfiguration();
//Android 7.0以上的方法
        if (VERSION.SDK_INT >= 24) {
            configuration.setLocale(locale);
            configuration.setLocales(new LocaleList(locale));
            context.createConfigurationContext(configuration);
//实测,updateConfiguration这个方法虽然很多博主说是版本不适用
//但是我的生产环境androidX+Android Q环境下,必须加上这一句,才可以通过重启App来切换语言
            resources.updateConfiguration(configuration, metrics);

        } else if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
//Android 4.1 以上方法
            configuration.setLocale(locale);
            resources.updateConfiguration(configuration, metrics);
        } else {
            configuration.locale = locale;
            resources.updateConfiguration(configuration, metrics);
        }
    }

3. 将用户选择保持到SharedPrefrence中, 通过在BaseActivity中来设置切换的动作

需要注意:在手动触发切换动作后, 需要退出所有的Activity, 重新启动,才会生效
原文地址:https://www.cnblogs.com/gloryhope/p/13293447.html