9

私たちのアプリでは、デバイスのロケールだけに依存するのではなく、ユーザーの選択に基づいて言語を変更できる必要があります。つまり、ユーザーがこの選択を行ったときにコンテキストをラップし、指定された言語をすべてのアクティビティに挿入する方法を実装する必要がありました。

    @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 を使用しているときに、ダーク モードを切り替えると、言語がデバイスの言語設定にリセットされることに気付きました。プロジェクトの appcompat のバージョンを 1.0.2 からアップグレードして、そのバージョンで壊れていたが1.1.0-alpha03MODE_NIGHT_FOLLOW_SYSTEMで修正済みとマークされているダーク モードを使用できるようにしたいと考えています。

この問題についてバグを報告しましたが、最新のappcompatを使用し、ダーク モードでカスタム言語を使用できるようにする回避策を誰かが見つけたのではないかと考えています。これは、この問題を示すプロジェクトです

4

0 に答える 0