You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android 10应用内语言切换功能失效问题求助

Android 10 应用内语言切换失效问题修复

针对你遇到的Android 10设备上语言切换失效的问题,可通过以下步骤修复:

1. 完善语言设置函数,适配Android 10及以下版本

Android 10(API 29)及以下系统中,仅调用AppCompatDelegate.setApplicationLocales可能无法立即更新当前Context的资源配置,需手动同步配置信息:

fun Context.setLanguage(language: String) {
    val locale = Locale.forLanguageTag(language)
    if (SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        this.getSystemService(LocaleManager::class.java).applicationLocales =
            LocaleList.forLanguageTags(language)
    } else {
        AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags(language))
        // 手动更新Context资源配置
        val resources = this.resources
        val configuration = resources.configuration.apply {
            setLocale(locale)
            setLayoutDirection(locale)
        }
        resources.updateConfiguration(configuration, resources.displayMetrics)
        // 同步Application Context的配置
        if (this is Application) {
            this.resources.updateConfiguration(configuration, this.resources.displayMetrics)
        }
    }
}

2. 优化Activity重启逻辑,清除旧实例

原重启方式可能残留旧配置的Activity实例,需添加栈清除标记:

fun Activity.startAgain() {
    val intent = Intent(this, javaClass).apply {
        addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    finish()
    startActivity(intent)
    overridePendingTransition(0, 0) // 可选,消除重启时的界面闪烁
}

3. 确保应用启动时初始化语言

在Application类的onCreate方法中,根据保存的偏好设置初始化语言,避免冷启动时配置不一致:

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        val prefs = AppPrefs(this)
        val targetLang = if (prefs.languageId == "1") ApiConstants.Language.EN else ApiConstants.Language.FR
        this.setLanguage(targetLang)
    }
}

4. 检查AppCompat依赖版本

确保使用支持AppCompatDelegate.setApplicationLocales的版本(需AppCompat 1.6.0及以上):

implementation 'androidx.appcompat:appcompat:1.6.1'

问题原因说明

  • Android 10及以下系统中,AppCompatDelegate.setApplicationLocales仅修改全局配置,但不会自动更新已创建的Context资源配置,需手动调用updateConfiguration同步。
  • 原重启逻辑未清除栈中旧Activity实例,可能导致新启动的Activity仍使用旧配置的Context。

内容的提问来源于stack exchange,提问作者user12741503

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:13:08