9

我们的应用程序要求我们能够根据用户选择更改语言,而不仅仅是依赖于设备区域设置。这意味着我们必须实现一种方法,以便我们在用户做出此选择时包装上下文并在每个 Activity 中注入指定的语言。

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LocaleProvider.getAppLocale().wrapContextWithAppLanguage(newBase));
    }
fun wrapContextWithAppLanguage(context: Context): Context {
        val userLocale: Locale = localeProvider.getCurrentStoreLanguage(context)
        Locale.setDefault(userLocale)

        return when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> updateResourcesLocale(
                context,
                userLocale
            )
            else -> updateResourcesLocaleLegacy(context, userLocale)
        }
    }

    @TargetApi(Build.VERSION_CODES.N)
    private fun updateResourcesLocale(context: Context, locale: Locale): Context {
        val configuration = context.resources.configuration
        configuration.setLocale(locale)
        return context.createConfigurationContext(configuration)
    }

    private fun updateResourcesLocaleLegacy(context: Context, locale: Locale): Context {
        val resources = context.resources
        val configuration = resources.configuration
        configuration.setLocale(locale)
        resources.updateConfiguration(configuration, resources.displayMetrics)
        return context
    }

这在过去对我们来说效果很好,但现在我们已经实现了暗模式,我们注意到切换暗模式会在使用 appcompat 1.1.0 时将语言重置为设备的语言设置。我们希望能够从 1.0.2 升级我们项目的 appcompat 版本,以便我们可以使用MODE_NIGHT_FOLLOW_SYSTEM在该版本中被破坏但在1.1.0-alpha03中标记为已修复的暗模式。

我已经针对这个问题提出了一个错误,但我想知道是否有人找到了一种解决方法,可以让我们使用最新的 appcompat 并允许在暗模式下使用自定义语言。这是一个演示此问题的项目

4

0 回答 0