在 Android Kotlin 中,可以使用以下步骤在切换语言时保留 Activity 状态:

  1. AndroidManifest.xml 文件中为 Activity 添加以下属性:
android:configChanges="locale"
  1. 在 Activity 中重写 onConfigurationChanged 方法:
override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    // 重新加载语言设置
    updateLanguage()
}
  1. updateLanguage 方法中重新加载语言设置:
private fun updateLanguage() {
    val locale = getSelectedLocale() // 获取用户选择的语言设置
    Locale.setDefault(locale)
    val config = resources.configuration
    config.setLocale(locale)
    resources.updateConfiguration(config, resources.displayMetrics)
    // 重新加载当前 Activity
    recreate()
}

以上步骤将在切换语言时保留 Activity 状态。

Android Kotlin 切换语言保留 Activity 状态 - configChanges 使用指南

原文地址: https://www.cveoy.top/t/topic/nDLl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录