首页 > 解决方案 > 为什么我的 Activity 语言在 Android 8 之前的设备上没有改变?

问题描述

当我的活动开始时,我想确保它使用正确的语言。我目前使用此代码来执行此操作:

    override fun attachBaseContext(newBase: Context) {
        val newContext = updateBaseContextLocale(newBase)
        super.attachBaseContext(newContext)
    }
    
    private fun updateBaseContextLocale(context: Context): Context {
        val locale = getMyLocale() // getMyLocale() gets the locale that should be used.
        Locale.setDefault(locale)
        
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            updateResourcesLocale(context, locale)
        } else {
            updateResourcesLocaleLegacy(context, locale)
        }
    }
    
    @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)
    }
    
    @Suppress("DEPRECATION")
    private fun updateResourcesLocaleLegacy(context: Context, locale: Locale): Context {
        val resources = context.resources
        val configuration = resources.configuration
        configuration.locale = locale
        resources.updateConfiguration(configuration, resources.displayMetrics)
        return context
    }

这会在 Android 8 和更新版本上产生正确的结果,但由于某种原因,该语言在旧版本的 Android 上保持不变。

调用updateBaseContextLocale(context: Context)函数onCreate似乎也没有改变任何东西。

我已经看到了这个问题,但我未能将那里的答案变成可行的解决方案。

我究竟做错了什么?

编辑:

我的最终目标是仅更改该 Activity 的语言,但如果仅更改一个 Activity 的语言是不可能的,那么更改整个 App 的语言也是可以接受的。

标签: androidlocalization

解决方案


推荐阅读