how can we programmatically switch language with t...
# compose
k
how can we programmatically switch language with the new composw resources?
@Konstantin Tskhovrebov
y
I made this object which I use to get my resources from either drawables or strings. if you noticed that in the getStringResource I have localization, you basically create an enum class with all your localization then you can provide a staticCompositionLocalOf with a state of your current localization
Copy code
object QrResources {
    @OptIn(ExperimentalResourceApi::class)
    fun getXmlPainterResource(image: String): DrawableResource {
        return DrawableResource("drawable/${image.removeSuffix(".xml")}.xml")
    }

    @OptIn(ExperimentalResourceApi::class)
    fun getPngPainterResource(image: String): DrawableResource {
        return DrawableResource("drawable/${image.removeSuffix(".png")}.png")
    }

    @OptIn(InternalResourceApi::class, ExperimentalResourceApi::class)
    fun getStringResource(
        res: String,
        localization: Localization = <http://Localization.Ar|Localization.Ar>,
    ): StringResource {
        return StringResource(
            "string:$res",
            res,
            setOf(
                ResourceItem(setOf(), "values${localization.value}/strings.xml"),
            ),
        )
    }
}

enum class Localization(val value: String) {
    Ar(""),
    En("-en"),
}
k
thats nice @youssef hachicha
but string paths are discouraged
y
what"s encouraged ?
k
generated Res class
👍 1
y
you cant use that in a multi-module project
k
you can with kotlin 2.0 but there are a few issues