Android篇——升级到androidx.appcompat.app.AppCompatActivity后,切换语言无效的解决办法。

有的同学提出,最近新写一个项目时,使用原来的语言切换工具类,却出现APP切换语言无效的问题,分析后发现是因为新项目使用了androidx的AppCompatActivity,而语言切换的代码却没有更新。

分析原因:

传统的切换语言方法都是重写attachBaseContext(Context newBase)方法,修改newBase的configuration,然后super.attachBaseContext(newBase);应用修改后的语言环境。

但是当升级androidx后,activity继承新的AppCompatActivity,语言环境不再由attachBaseContext得到的Context对象去处理,而是新的AppCompatActivity额外套的一层ContextThemeWrapper负责(下面代码中的wrappedContext对象),(有兴趣的同学可以去阅读AppCompatActivity的源码)。我们需要将语言变更设置给wrappedContext,再super.attachBaseContext(wrappedContext);  这样就可以正常切换语言了。

解决办法:(在使用androidx的情况下)

@Override
protected void attachBaseContext(Context newBase) {
    Resources resources = newBase.getResources();
    Configuration configuration = resources.getConfiguration();
    int language = xxx(); //你要设置的语言,我这里举例是3种,0英文,1繁体中文,2简体中文
    Locale targetLocale = language == 0 ? Locale.US : language == 1 ? Locale.TRADITIONAL_CHINESE : Locale.SIMPLIFIED_CHINESE;

    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);
}

猜你喜欢

转载自blog.csdn.net/u011391361/article/details/122813927
今日推荐