首页 > 解决方案 > 使用类 ContextWrapper 更改语言 Android 应用程序在发布模式下不起作用

问题描述

我已经实现了这段代码来更改应用程序的语言,它在具有 API 23、24、25、26、27 和 28 的模拟器中以及在以“Active Build Variant”模式在“调试”中安装时也可以在真实设备中正常工作"状态

信息: Android N 以编程方式更改语言

但是,当我在“发布”状态下以“Active Build Variant”模式将应用程序上传到 Google Play 商店时,语言更改在真实设备上不起作用

那可能会发生吗?我不知道该怎么处理这个问题了。如果您能帮助我,我将不胜感激。谢谢

我的方法静态 ContextWrapper,类 Config:

    public static ContextWrapper changeLang(Context context, String lang_code){
    Locale sysLocale;

    Resources rs = context.getResources();
    Configuration config = rs.getConfiguration();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        sysLocale = config.getLocales().get(0);
    } else {
        sysLocale = config.locale;
    }

    if ( !lang_code.equals("") ) {
        Locale locale = new Locale(lang_code);
        Locale.setDefault(locale);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            config.setLocale(locale);
        } else {
            config.locale = locale;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            context = context.createConfigurationContext(config);
        } else {
            context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
        }
    }

    return new ContextWrapper(context);
}

我的活动代码

    @Override
protected void attachBaseContext(Context newBase) {
    pref = PreferenceManager.getDefaultSharedPreferences( newBase );
    String lang_code = pref.getString("LANG_APP","");

    Context context = Config.changeLang(newBase, lang_code);
    super.attachBaseContext(context);
}

那可能会发生吗?我不知道该怎么处理这个问题了。如果您能帮助我,我将不胜感激。谢谢

标签: androidandroid-studio

解决方案


这个解决方案对我有用

android {
bundle {
    language {
        // Specifies that the app bundle should not support
        // configuration APKs for language resources. These
        // resources are instead packaged with each base and
        // dynamic feature APK.
        enableSplit = false
    }
}
}

问题可能是Android BUNDLE,如果您构建 BUNDLE(不是 apk)它会删除 apk 文件中的语言 .xml。如果您编写上述代码,则在创建 .aab 捆绑文件时不会删除 language.xml。


推荐阅读