Abdalla Hassanin

    Abdalla Hassanin

    1 year ago
    how to Localization my app in compose without string XML file
    z

    Zun

    1 year ago
    Why don’t you want to use string resource?
    t

    Tin Tran

    1 year ago
    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
    Abdalla Hassanin

    Abdalla Hassanin

    1 year ago
    @Zun I want to know if there is an alternative way to xml for the sake of knowing
    Albert Chang

    Albert Chang

    1 year ago
    Just create a map for each locale and switch the map according to
    LocalConfiguration.current.locales
    .
    Abdalla Hassanin

    Abdalla Hassanin

    1 year ago
    @Albert Chang Please if you have an example to understand this
    Albert Chang

    Albert Chang

    1 year ago
    A simplest example:
    // 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.
    Chachako

    Chachako

    1 year ago
    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
    Abdalla Hassanin

    Abdalla Hassanin

    1 year ago
    @Albert Chang @Chachako Thank you
    Albert Chang

    Albert Chang

    1 year ago
    @Chachako
    Locale.current
    won't trigger recomposition on locale change.
    Chachako

    Chachako

    1 year ago
    @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?
    Albert Chang

    Albert Chang

    1 year ago
    @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.