
Kotlin Multiplatform i18n: Sdílená lokalizace napříč platformami
Napište překlady jednou ve sdíleném Kotlin kódu. Doručte je na Android, iOS a web se správnými fallback řetězci pro locale.
Nakonfigurovat Gradle pro KMP i18n
Přidejte závislosti pro i18n do source setu commonMain ve sdíleném modulu. Můžete zvolit moko-resources pro řetězce v XML, Lyricist pro typově bezpečné řetězce v Compose, nebo obojí. kmp-localechain nad nimi přidá chytrý fallback pro locale.
// build.gradle.kts (shared module)
plugins {
kotlin("multiplatform")
id("com.android.library")
}
kotlin {
androidTarget()
iosArm64()
iosSimulatorArm64()
js(IR) { browser(); nodejs() }
sourceSets {
val commonMain by getting {
dependencies {
// Option A: moko-resources (code-gen from XML)
implementation("dev.icerock.moko:resources:0.24.4")
// Option B: Lyricist (type-safe Compose strings)
implementation("cafe.adriel.lyricist:lyricist:1.7.0")
// Locale fallback chains (works with any library)
implementation("com.i18nagent:locale-chain-kmp:0.1.0")
}
}
}
}Zapojit Android
V androidMain implementujte expect/actual pattern pro čtení locale zařízení přes java.util.Locale. Android může používat sdílené Kotlin řetězce pro business logiku vedle standardních values/strings.xml pro systémové prvky UI, jako jsou notifikace a widgety.
// androidMain/kotlin/com/myapp/StringProvider.kt
package com.myapp.i18n
import java.util.Locale
actual fun currentLocale(): String =
Locale.getDefault().toLanguageTag() // e.g. "pt-BR"
// Android can also use standard resources/values-*/strings.xml
// alongside the shared Kotlin definitions.
// Use shared strings for business logic, XML for system UI.
// In your Activity or Compose screen:
@Composable
fun GreetingScreen() {
val strings = rememberStrings() // resolves via locale
Text(text = strings.greeting)
Text(text = strings.itemCount(cartSize))
}Zapojit iOS
V iosMain implementujte currentLocale() pomocí NSLocale z Foundation. Sdílený KMP framework exportuje Vaše definice řetězců do Swiftu, takže je SwiftUI views mohou volat přímo přes vygenerovaný Kotlin framework.
// iosMain/kotlin/com/myapp/StringProvider.kt
package com.myapp.i18n
import platform.Foundation.NSLocale
import platform.Foundation.currentLocale
import platform.Foundation.languageCode
import platform.Foundation.countryCode
actual fun currentLocale(): String {
val locale = NSLocale.currentLocale
val lang = locale.languageCode
val country = locale.countryCode
return if (country != null) "$lang-$country" else lang
}
// In SwiftUI (via KMP exported framework):
// let strings = StringProviderKt.stringsFor(locale: "ja")
// Text(strings.greeting)Zapojit JS/Browser
V jsMain čtěte locale prohlížeče z window.navigator.language. To pokrývá jak Kotlin/JS webové aplikace, tak targety Compose for Web. Stejné sdílené řetězce se v prohlížeči vykreslí bez jakékoli duplicity.
// jsMain/kotlin/com/myapp/StringProvider.kt
package com.myapp.i18n
import kotlinx.browser.window
actual fun currentLocale(): String =
window.navigator.language // e.g. "en-US", "pt-BR"
// In a Kotlin/JS or Compose for Web app:
fun main() {
val locale = currentLocale()
val strings = stringsFor(locale)
document.getElementById("greeting")?.textContent = strings.greeting
}Lyricist pro Compose Multiplatform
Lyricist poskytuje Compose-native přístup k i18n. Anotujte Vaše string objekty pomocí @LyricistStrings a Lyricist vygeneruje provider pro CompositionLocal. Jazyky přepínejte za běhu změnou languageTag — UI se automaticky překomponuje.
// Using Lyricist for Compose Multiplatform
// build.gradle.kts
plugins {
id("cafe.adriel.lyricist") version "1.7.0"
}
// Define strings with @LyricistStrings annotation
@LyricistStrings(languageTag = Locales.EN, default = true)
val EnStrings = Strings(
greeting = "Hello!",
farewell = "Goodbye!",
itemCount = { count ->
if (count == 1) "$count item" else "$count items"
},
)
@LyricistStrings(languageTag = Locales.JA)
val JaStrings = Strings(
greeting = "こんにちは!",
farewell = "さようなら!",
itemCount = { count -> "${count}個のアイテム" },
)
// In your Compose UI
@Composable
fun App() {
// Lyricist provides the strings via CompositionLocal
ProvideStrings {
val lyricist = LocalStrings.current
Text(text = lyricist.greeting)
}
}
// Switch language at runtime
val lyricist = rememberLyricist(
defaultLanguageTag = Locales.EN,
)
lyricist.languageTag = Locales.JA // UI recomposes automaticallymoko-resources pro XML řetězce
moko-resources používá stringy ve formátu Android-style XML jako zdroj pravdy a generuje typově bezpečné přístupové metody. Definujte řetězce v commonMain/resources/MR/base/ (angličtina) a pro každý jazyk přidejte složky pro jednotlivá locale. Vygenerovaný objekt MR poskytuje přístup kontrolovaný při kompilaci.
// Using moko-resources for XML-based string management
// build.gradle.kts
plugins {
id("dev.icerock.mobile.multiplatform-resources") version "0.24.4"
}
multiplatformResources {
resourcesPackage.set("com.myapp")
}
// commonMain/resources/MR/base/strings.xml (English - default)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="greeting">Hello!</string>
<string name="farewell">Goodbye!</string>
<plurals name="item_count">
<item quantity="one">%d item</item>
<item quantity="other">%d items</item>
</plurals>
</resources>
// commonMain/resources/MR/ja/strings.xml (Japanese)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="greeting">こんにちは!</string>
<string name="farewell">さようなら!</string>
<plurals name="item_count">
<item quantity="other">%d個のアイテム</item>
</plurals>
</resources>
// Usage in shared Kotlin code
val greeting = MR.strings.greeting.desc()
val items = MR.plurals.item_count.format(count)Chytrý fallback locale s kmp-localechain
KMP i18n knihovny postrádají konfigurovatelné fallback řetězce. Když chybí překlady pt-BR, úplně přeskočí pt-PT a zobrazí angličtinu. kmp-localechain to řeší samostatnou utilitou pro slučování zpráv. Bere pro každé locale ploché Map<String, String> se zprávami a vrací sloučenou mapu s aplikovanou prioritou fallback řetězce.
// Using kmp-localechain for smart locale fallback
import com.i18nagent.localechain.LocaleChain
// 1. Configure once at app startup
LocaleChain.configure() // uses built-in fallback chains
// 2. Load your messages as flat maps
val messages = mapOf(
"en" to mapOf("greeting" to "Hello", "farewell" to "Goodbye"),
"pt" to mapOf("greeting" to "Olá", "farewell" to "Adeus"),
"pt-PT" to mapOf("greeting" to "Olá (PT)"),
"pt-BR" to mapOf("greeting" to "Oi"),
)
// 3. Resolve with chain priority
val resolved = LocaleChain.resolve("pt-BR", messages)
// "greeting" -> "Oi" (from pt-BR, most specific)
// "farewell" -> "Adeus" (from pt, next in chain)
// Without LocaleChain, pt-BR users would see English "Goodbye"
// because pt-BR has no "farewell" key.// Custom fallback configuration
LocaleChain.configure(
defaultLocale = "en",
overrides = mapOf(
"es-MX" to listOf("es-419", "es"),
"fr-CA" to listOf("fr"),
)
)
// Inspect any chain
LocaleChain.chainFor("pt-BR")
// Returns: ["pt-BR", "pt-PT", "pt", "en"]
// Async resolve (lazy loading from network/disk)
val resolved = LocaleChain.resolve("pt-BR") { localeTag ->
api.fetchMessages(localeTag) // returns Map<String, String>?
}Automatizovat překlady
Jakmile máte KMP i18n nastavení hotové, automatizujte překlady pomocí AI. Překládejte sdílené soubory s řetězci — ať už jde o Kotlin datové třídy, XML resources nebo JSON — přímo z Vašeho IDE nebo z CI/CD pipeline.
# Translate your shared string files with i18n Agent
# Works with JSON, XML (moko-resources), or any i18n format
# From your IDE (Claude Code, Cursor, VS Code):
> Translate commonMain/resources/MR/base/strings.xml to Japanese, German, and Spanish
✓ MR/ja/strings.xml created (1.2s)
✓ MR/de/strings.xml created (1.1s)
✓ MR/es/strings.xml created (1.3s)
# Or use the CLI in CI/CD:
npx i18n-agent translate resources/base/strings.xml --lang ja,de,esAutomatizovat kvalitu překladu
Běžné pasti
Neshoda expect/actual
Natvrdo zapsaná logika plurálů
Vnořené mapy v kmp-localechain
Chybějící vygenerovaný kód po přidání moko-resources
Doporučená struktura projektu
my-kmp-app/
├── shared/
│ ├── build.gradle.kts
│ └── src/
│ ├── commonMain/
│ │ ├── kotlin/com/myapp/i18n/
│ │ │ ├── Strings.kt # Shared string definitions
│ │ │ ├── StringProvider.kt # expect fun currentLocale()
│ │ │ └── LocaleSetup.kt # LocaleChain configuration
│ │ └── resources/MR/ # moko-resources XML (optional)
│ │ ├── base/strings.xml # English (default)
│ │ ├── ja/strings.xml
│ │ ├── de/strings.xml
│ │ └── es/strings.xml
│ ├── androidMain/
│ │ └── kotlin/com/myapp/i18n/
│ │ └── StringProvider.kt # actual fun currentLocale()
│ ├── iosMain/
│ │ └── kotlin/com/myapp/i18n/
│ │ └── StringProvider.kt # actual fun currentLocale()
│ └── jsMain/
│ └── kotlin/com/myapp/i18n/
│ └── StringProvider.kt # actual fun currentLocale()
├── androidApp/
│ └── src/main/res/values/strings.xml # Android-specific overrides
├── iosApp/
│ └── iosApp/Localizable.strings # iOS-specific overrides
└── settings.gradle.ktsVyzkoušejte i18n Agent nyní
Sem přetáhněte svůj překladový soubor
JSON, YAML, PO, XML, CSV, Markdown, Properties
nebo klikněte a vyberte soubor
Cílové jazyky