how to Localization my app in compose without stri...
# compose
a
how to Localization my app in compose without string XML file
z
Why don’t you want to use string resource?
t
Im having the same requirement. I have to get string resources from an API. Currently I have to store them into a map and fetch strings from there
a
@Zun I want to know if there is an alternative way to xml for the sake of knowing
a
Just create a map for each locale and switch the map according to
LocalConfiguration.current.locales
.
☝️ 1
a
@Albert Chang Please if you have an example to understand this
a
A simplest example:
Copy code
// Strings.kt
private val EnUs = mapOf(
    "hello" to "Hello"
)

private val FrFr = mapOf(
    "hello" to "Bonjour"
)

@Composable
fun string(key: String): String {
    val map = when(LocalConfiguration.current.locales.get(0)) {
        Locale.forLanguageTag("fr-FR") -> FrFr,
        else -> EnUs
    }
    return map.getValue(key)
}

// UI code
@Composable
fun Greeting() {
    Text(text = string("hello"))
}
Note that I’ve simplified many things. You shouldn’t just use the first locale in the locale list, and locale matching is much more complicated than this. Also you probably want to cache the map for current locale as locale matching is rather expensive.
🙌 2
c
I also didn’t use xml in Jetpack-Compose Challenge 1. This is my approach (for reference only): https://github.com/RinOrz/compose-kitty/blob/main/app/src/main/kotlin/com/rin/compose/kitty/data/S.kt
🙌 1
a
@Albert Chang @Chachako Thank you
a
@Chachako
Locale.current
won't trigger recomposition on locale change.
c
@Albert Chang Should I be able to monitor the changes in the language environment in other ways and then recomposition?
I don’t think it is necessary for each string to know when the locale is changed. My understanding is that only need to update the composable tree after the locale changes?
a
@Chachako Just use
LocalConfiguration
as it is monitored by the runtime. It's a waste to recompose the whole tree when you can only recompose part of it. The whole point of compose compiler plugin is to enable compose runtime to only recompose what needs to be recomposed. And anyway you need to notify the runtime when locale changes.
👍🏼 1
👍 1