how to Localization my app in compose without stri...
# compose
how to Localization my app in compose without string XML file
Why don’t you want to use string resource?
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
@Zun I want to know if there is an alternative way to xml for the sake of knowing
Just create a map for each locale and switch the map according to
☝️ 1
@Albert Chang Please if you have an example to understand this
A simplest example:
Copy code
// Strings.kt
private val EnUs = mapOf(
    "hello" to "Hello"

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

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
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
I also didn’t use xml in Jetpack-Compose Challenge 1. This is my approach (for reference only):
🙌 1
@Albert Chang @Chachako Thank you
won't trigger recomposition on locale change.
@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?
@Chachako Just use
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