zsperske
09/29/2022, 4:33 PMR.attr
references in a Compose Preview? We use attribute references & themes for colors/drawables/text styles, however when running a preview they don’t resolve properly. This Composable fails to render a Preview.
@Preview
@Composable
fun MyComposable() {
val attrPainter = attrPainter(R.attr.myAttr) //custom painter to get a drawable from an attr reference
Image(attrPainter, contentDescription = "some description")
}
mattinger
09/29/2022, 6:17 PMzsperske
09/29/2022, 6:22 PMmattinger
09/29/2022, 6:27 PMmattinger
09/29/2022, 6:32 PMinterface MyDrawables {
val zoom: Int
}
val LocalMyDrawables = staticCompositionLocalOf<MyDrawables> {
object: MyDrawables {
override val zoom: Int
get() = R.drawable.cl_ic_zoom_outline
}
}
val MaterialTheme.myDrawables @Composable get() = LocalMyDrawables.current
mattinger
09/29/2022, 6:33 PMmattinger
09/29/2022, 6:34 PM@Composable
fun MyTheme(
colors: Colors = MaterialTheme.colors,
typography: Typography = MaterialTheme.typography,
shapes: Shapes = MaterialTheme.shapes,
drawables: MyDrawables = object : MyDrawables {
override val zoom: Int
get() = R.drawable.cl_ic_zoom_outline
},
content: @Composable () -> Unit
) {
MaterialTheme(colors, typography, shapes) {
CompositionLocalProvider(
LocalMyDrawables provides drawables
) {
content()
}
}
}
zsperske
09/29/2022, 6:35 PMmattinger
09/29/2022, 6:36 PMmattinger
09/29/2022, 6:42 PMmattinger
09/29/2022, 6:49 PM@Preview
@Composable
fun MyPreview() {
val context = LocalContext.current
val wrapper = ContextThemeWrapper(context, R.style.Theme_MaterialComponents)
CompositionLocalProvider(
LocalContext provides wrapper
) {
Box(modifier = Modifier
.size(50.dp)
.background(attrColorResource(attrId = R.attr.colorPrimary))) {
}
}
}
@Composable
fun attrColorResource(attrId: Int): Color {
val context = LocalContext.current
val attrs = context.theme.obtainStyledAttributes(intArrayOf(attrId))
val colorValue = attrs.getColor(0, 0)
return Color(colorValue)
}
mattinger
09/29/2022, 6:50 PMzsperske
09/29/2022, 6:51 PMzsperske
09/29/2022, 10:51 PMzsperske
09/29/2022, 10:51 PM