icerockdev / moko-resources

Resources access for mobile (android & ios) Kotlin Multiplatform development
https://moko.icerock.dev/
Apache License 2.0
1.12k stars 124 forks source link

Using Localization String in KMM #753

Open mikek9084 opened 3 months ago

mikek9084 commented 3 months ago

thank you very much, how can I use SharedRes. in common main

buildString {
        append("Limit)
        append(SharedRes.strings.km)
}
mndsl commented 2 months ago

You have to use expect/actual functions in commonMain:

expect fun sharedString(res: StringResource, vararg args: Any): String

in androidMain:

[!NOTE] You will need context

actual fun sharedString(res: StringResource, vararg args: Any): String {
return when (args.size) {
0    -> res.getString(context)
else -> ResourceFormattedStringDesc(res, args.toList()).toString(context)
}
}

in iosMain:

actual fun sharedString(res: StringResource, vararg args: Any): String {
return when (args.size) {
0    -> res.desc().localized()
else -> ResourceFormattedStringDesc(res, args.toList()).localized()
}
}

Then in commonMain you can get any string like this:

val text = sharedString(MR.strings.my_string)
val text = sharedString(MR.strings.my_string_formatted, 10)