Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Theme dependent resources in compose

Is there any way to use theme dependent strings and drawables in Jetpack Compose? In xml-based layouts, it could be done using attributes and themes.

like image 904
Android Newcomer Avatar asked Oct 26 '25 15:10

Android Newcomer


1 Answers

You can create your own local variable, something like this:

data class AppResources(
    @DrawableRes val someDrawable: Int,
    @StringRes val someString: Int,
)

val LocalAppResources = staticCompositionLocalOf<AppResources> {
    error("CompositionLocal LocalAppResources not present")
}

Provide needed values in your theme:

val LightAppResources = AppResources(
    someDrawable = R.drawable.drawable_light,
    someString = R.string.text_light
)

val DarkAppResources = AppResources(
    someDrawable = R.drawable.drawable_dark,
    someString = R.string.text_dark
)

@Composable
fun AppTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit
) {
    val colors = if (darkTheme) {
        DarkThemeColors
    } else {
        LightThemeColors
    }
    val appResources = if (darkTheme) {
        DarkAppResources
    } else {
        LightAppResources
    }
    MaterialTheme(
        colors = colors,
        typography = typography,
        shapes = shapes,
    ) {
        CompositionLocalProvider(
            LocalAppResources provides appResources,
            content = content
        )
    }
}

And then you can use it in your app like this:

Image(
    painterResource(id = LocalAppResources.current.someDrawable),
    "..."
)
Text(
    stringResource(id = LocalAppResources.current.someString)
)
like image 141
Philip Dukhov Avatar answered Oct 29 '25 05:10

Philip Dukhov