首页 > 解决方案 > 运行时应用程序本地化不适用于应用程序包

问题描述

对于不同的语言,我有不同的字符串值。在运行时,用户可以选择另一种语言。minSdkVersion 21

我正在使用这些方法更新语言环境

public static Context setNewLocale(Context c, String language) {
    persistLanguage(c, language); // persists new language in shared prefs
    return updateResources(c, language);
}

private static Context updateResources(Context context, String language) {
    Locale locale = new Locale(language, language + "_" + language.toUpperCase());
    Locale.setDefault(locale);
    Resources res = context.getResources();
    Configuration config = res.getConfiguration();
    config.setLocale(locale);
    context = context.createConfigurationContext(config);
    return context;
}

并且有一个 BaseActivity 我已经覆盖了 attachBaseContext,每个活动都扩展了它。

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(LocaleManager.setLocale(base));
}

并且在 BaseApplication 中也被覆盖

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(LocaleManager.setLocale(base)); //updates resources
    MultiDex.install(getBaseContext());
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    LocaleManager.setLocale(this); //updates resources
}

用户选择新语言后,我正在重新创建活动。当我从商店下载发布版本时,所有这些在调试时都可以正常工作,但该应用程序仅使用默认语言。改变语言也无济于事。

标签: android

解决方案


首先,问题不在于代码,而在于 Android 使用新应用程序包处理资源的方式发生了变化。以前使用 APK 下载了所有资源。现在它只下载您的手机符合条件的资源。如果您的首选语言只有英语,它不会下载其他语言,除非……您另有说明

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
    }
    density {
        // This property is set to true by default.
        enableSplit = true
    }
    abi {
        // This property is set to true by default.
        enableSplit = true
    }
}

推荐阅读