国际化

通过英文和中文资源实现运行时语言切换。

Kotlin 模板使用 Android string resources 本地化用户可见文本:values/strings.xml 是英文, values-zh/strings.xml 是中文。Compose 中的运行时语言切换不需要重启 activity。

提供什么

Surface状态实现
English resourcesIntegratedapp/src/main/res/values/strings.xml
Chinese resourcesIntegratedapp/src/main/res/values-zh/strings.xml
Runtime switchIntegratedLocaleController + LocalizedAppHost
持久化IntegratedDataStore key language_tag
Picker labelsIntegratedAppLanguage enum 携带 localized label resource ids

关键文件

切换如何工作

LocaleController 把 DataStore 中的 language_tag string 映射为 AppLanguage

enum class AppLanguage(val tag: String, val labelResId: Int) {
    English("en", R.string.language_english),
    Chinese("zh", R.string.language_chinese)
}

MainActivityLocalizedAppHost 包裹应用。host 使用 Locale.forLanguageTag(language.tag) 创建 localized Context,然后通过 Compose locals 提供 context 和 configuration:

LocaleController.selectedLanguage
  -> LocalizedAppHost
  -> LocalContext / LocalConfiguration
  -> stringResource(...)

因为 localized context 在 composition 内提供,切换语言会在当前 session 更新可见 Compose strings, 不需要 activity restart。

Resource 规则

把所有用户可见文案放进 resources:

<string name="notifications_title">Notifications</string>

然后在 Compose 中读取:

Text(stringResource(R.string.notifications_title))

避免在 composables 中硬编码 screen labels、button text、validation messages 和 demo copy。当前 Component gallery catalog 是需要审计的区域:它的 entries 仍是 plain Kotlin strings。

添加语言

添加 resource folder

创建新的 Android resource folder,例如:

app/src/main/res/values-ja/strings.xml

复制英文 keys 并翻译每个 value。

添加 enum case

扩展 AppLanguage

Japanese("ja", R.string.language_japanese)

同时在每个已有 strings.xml 中添加 language_japanese

重建并测试

运行应用,打开 drawer language picker,切换语言,并确认当前 screen 不退出也能更新可见文本。

验证

  • values/strings.xml 中的每个 key 都存在于 values-zh/strings.xml
  • 面向产品的文案没有硬编码在 feature screens 中。
  • Drawer language picker 在应用重启后仍保留选择。
  • 切换语言会更新 nested screens 和 dialogs,而不仅是 top-level tabs。
  • Play review notes、legal URLs 等 release-only strings 在 APK 外适当处理。

相关页面

On this page