9

Our app requires us to be able to change the language based on user selection rather than just relying on the device locale. This means we've had to implement a way for us to wrap the context when a user makes this selection and inject the specified language in every 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
    }

This has worked well for us in the past but now that we've implemented Dark Mode, we've noticed that toggling Dark Mode resets the language to the device's language setting when using appcompat 1.1.0. We'd like to be able to upgrade our project's version of appcompat from 1.0.2 so that we can use Dark Mode MODE_NIGHT_FOLLOW_SYSTEM which was broken in that version but marked as fixed in 1.1.0-alpha03.

I've raised a bug for this issue but I'm wondering if anybody has found a workaround that'll allow us to use the latest appcompat and allow for custom languages with Dark Mode. Here's a project that demonstrates this issue.

HBG
  • 1,731
  • 2
  • 23
  • 35
  • 2
    Take a look at the work around mentioned here https://stackoverflow.com/questions/55265834/change-locale-not-work-after-migrate-to-androidx/58004553#58004553 – Ankit Batra Jun 26 '20 at 17:42

0 Answers0