栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

升级到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);
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/733239.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号