Android升 Androidx 语系切换失效

发布时间 2023-11-09 15:32:42作者: 人间春风意

背景:

一个很旧的Android项目,android升androidx

切换语系失败,debug的时候,传的语系值是对的,但是确实没有国际化效果

原因:

经过一番学习,原因是使用 implementation 'androidx.appcompat:appcompat:1.0.2'

原本Android的写法不适用于Androidx,调整后的代码,指定语系可以切换,但是跟随系统语系一直不生效

又调整了获取当前设备默认Local的方法

 

方案:

Application和BaseActivity中添加:

    @Override
    protected void attachBaseContext(Context newBase) {
        Resources resources = newBase.getResources();
        Configuration configuration = resources.getConfiguration();
        Locale targetLocale = getSetLanguageLocale(newBase);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LocaleList localeList = new LocaleList(targetLocale);
            LocaleList.setDefault(localeList);
            configuration.setLocales(localeList);
        } else {
            configuration.setLocale(targetLocale);
        }
        Context targetContext = newBase.createConfigurationContext(configuration);
        final ContextThemeWrapper wrappedContext = new ContextThemeWrapper(targetContext, R.style.Theme_AppCompat_Empty) {
            @Override
            public void applyOverrideConfiguration(Configuration overrideConfiguration) {
                if (overrideConfiguration != null) {
                    overrideConfiguration.setTo(configuration);
                }
                super.applyOverrideConfiguration(overrideConfiguration);
            }
        };
        super.attachBaseContext(wrappedContext);
    }

 其中为默认语系时,Local为:

Resources.getSystem().getConfiguration().locale