渐进式编程课
KMP 目录
第 22 课2026.08.07

把文案直接写在 Kotlin 代码里,会让翻译、地区适配和统一修改变得困难。Compose Multiplatform 可以在 commonMain 维护共享字符串资源,并根据设备语言自动选择对应翻译。

第 22 课:Compose 共享资源与本地化

  • 日期:2026-08-07
  • 课程序号:22
  • 知识点:使用 composeResources 和 stringResource() 管理多平台文案

用途

把文案直接写在 Kotlin 代码里,会让翻译、地区适配和统一修改变得困难。Compose Multiplatform 可以在 commonMain 维护共享字符串资源,并根据设备语言自动选择对应翻译。

核心概念

  • 默认字符串放在 commonMain/composeResources/values/strings.xml。
  • 翻译放在带语言限定符的目录,例如 values-zh。
  • 构建项目后,插件会生成类型安全的 Res.strings 访问器。
  • stringResource() 在可组合函数中读取当前语言对应的文案。
  • 缺少某个翻译时,会回退到默认 values 资源。

示例代码

在共享 UI 模块加入资源依赖:

kotlin
kotlin {
    sourceSets {
        commonMain.dependencies {
            implementation(compose.components.resources)
        }
    }
}

默认资源 commonMain/composeResources/values/strings.xml:

xml
<resources>
    <string name="app_title">KMP Learning</string>
    <string name="welcome_message">Welcome, %s!</string>
</resources>

中文资源 commonMain/composeResources/values-zh/strings.xml:

xml
<resources>
    <string name="app_title">KMP 学习</string>
    <string name="welcome_message">欢迎你,%s!</string>
</resources>

构建项目生成访问器后,在 commonMain 使用资源:

kotlin
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import org.jetbrains.compose.resources.stringResource
import your.project.generated.resources.Res

@Composable
fun WelcomeScreen(userName: String) {
    Column {
        Text(
            text = stringResource(Res.strings.app_title),
        )
        Text(
            text = stringResource(
                Res.strings.welcome_message,
                userName,
            ),
        )
    }
}

your.project.generated.resources 需要替换成当前模块实际生成的资源包名。系统语言为中文时显示中文资源,否则使用匹配语言或默认文案。

5 分钟练习

添加字符串资源 retry_label:默认文案为 Retry,中文文案为 重试,然后把它用作错误页面按钮文字。

参考答案

默认 strings.xml:

xml
<string name="retry_label">Retry</string>

中文 strings.xml:

xml
<string name="retry_label">重试</string>

Compose 代码:

kotlin
Button(onClick = onRetry) {
    Text(
        text = stringResource(Res.strings.retry_label),
    )
}

按钮文案由资源环境决定,业务错误类型和重试事件语义保持不变。

与上一课的联系

上一课用 Android 与 iOS 平台入口承载同一个共享 App();本课让这套共享 UI 在不同平台和语言环境中自动选择对应文案,不需要在平台入口编写两套字符串。

参考资料