项目的多语言突然失效了,就很奇怪,根本没碰过这方面的代码

总之找到原因了,androidx.appcompat:appcompat 的版本不经意间升到1.2.0导致的问题

按照大佬的方法修改后还是不行
https://zhuanlan.zhihu.com/p/259595928

然后在外网找到了解决方法。就是 getConfiguration 要new 出来就行了

https://issuetracker.google.com/issues/140602653
https://stackoverflow.com/questions/63461719/changing-locale-stopped-working-in-android-10

之前的代码:

    @Override
    protected void attachBaseContext(Context newBase) {
        int languageId = SP.getInstance().getLanguageId();
        LanguageUtils.setDefaultLanguage(newBase, languageId);
        super.attachBaseContext(newBase);

    }

改之后的代码

@Override
    protected void attachBaseContext(Context newBase) {
        int languageId = SP.getInstance().getLanguageId();
        Context context = LanguageUtils.setDefaultLanguage(newBase, languageId);
        final Configuration configuration = new Configuration();
        // 此处的ContextThemeWrapper是androidx.appcompat.view包下的
        // 你也可以使用android.view.ContextThemeWrapper,但是使用该对象最低只兼容到API 17
        // 所以使用 androidx.appcompat.view.ContextThemeWrapper省心
        final ContextThemeWrapper wrappedContext = new ContextThemeWrapper(context,
                R.style.Base_Theme_NoActionBar) {
            @Override
            public void applyOverrideConfiguration(Configuration overrideConfiguration) {
                if (overrideConfiguration != null) {
                    overrideConfiguration.setTo(configuration);
                }
                super.applyOverrideConfiguration(overrideConfiguration);
            }
        };
        super.attachBaseContext(wrappedContext);
    }

标签: android

添加新评论