Home > Back-end >  Theme dependent resources in compose
Theme dependent resources in compose

Time:09-21

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.

CodePudding user response:

Do you need to internationalize them? you could just create references in your theme object.

Or make an custom strings class that you can load when you create your theme. i.e. just pass in the result of stringResource(R.string.xxx,...)

Themes are more functional so shouldn't be hard to do it.

CodePudding user response:

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)
)
  • Related