Android Kotlin 切换语言保留 Activity 状态 - configChanges 使用指南
在 Android Kotlin 中,可以使用以下步骤在切换语言时保留 Activity 状态:
- 在
AndroidManifest.xml文件中为 Activity 添加以下属性:
android:configChanges="locale"
- 在 Activity 中重写
onConfigurationChanged方法:
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// 重新加载语言设置
updateLanguage()
}
- 在
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 状态。
原文地址: https://www.cveoy.top/t/topic/nDLl 著作权归作者所有。请勿转载和采集!