Kotlin Jetpack Compose中注入Context获取多语言资源失败
问题原因及解决方法
核心原因
你注入的是ApplicationContext,它的Locale是应用启动时的系统语言,后续系统语言切换后不会自动更新,导致始终返回默认语言的字符串。
解决步骤
1. 修改ResourceControllerImpl,动态适配当前Locale
每次获取字符串时,基于当前系统Locale创建新的Context,确保拿到对应语言的资源:
class ResourceControllerImpl @Inject constructor(private val context: Context) : ResourceController { override fun getString(resourceId: Int): String { // 获取当前系统的Locale val currentLocale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Resources.getSystem().configuration.locales[0] } else { @Suppress("DEPRECATION") Resources.getSystem().configuration.locale } // 创建适配当前Locale的Configuration val updatedConfig = Configuration(context.resources.configuration).apply { setLocale(currentLocale) } // 创建本地化Context并获取字符串 val localizedContext = context.createConfigurationContext(updatedConfig) return localizedContext.getString(resourceId) } }
2. 检查资源文件配置
确认你的语言资源文件命名和位置正确:
- 西班牙语:
res/values-es/strings.xml - 英语:
res/values-en/strings.xml - 法语:
res/values-fr/strings.xml - 意大利语:
res/values-it/strings.xml - 德语:
res/values-de/strings.xml - 加泰罗尼亚语:
res/values-ca/strings.xml
确保每个文件中都包含R.string.serial_number_label对应的翻译,没有拼写错误。
3. 避免锁定Locale的配置
检查Manifest中是否设置了android:configChanges="locale",如果设置了,系统语言切换时不会自动重启应用更新配置,建议移除该配置(如果业务允许),或者在Activity的onConfigurationChanged中手动处理配置更新。
4. 应用内切换语言的补充处理
如果是应用内手动切换语言(而非依赖系统语言),需要确保切换后更新应用全局配置,并通知系统:
fun updateAppLocale(context: Context, targetLocale: Locale) { val resources = context.resources val config = Configuration(resources.configuration).apply { setLocale(targetLocale) } resources.updateConfiguration(config, resources.displayMetrics) // 发送广播通知配置变化 context.sendBroadcast(Intent(Intent.ACTION_LOCALE_CHANGED)) }
内容的提问来源于stack exchange,提问作者Didier Vera
相关产品推荐
相关产品推荐

