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.
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With