https://kotlinlang.org logo
#compose
Title
# compose
a

alorma

03/13/2024, 7:17 PM
Hi! I’m trying to use
@PreviewDynamicColors
with no success... Always show the same primary color from my theme definition... Is there any examples of that feature? As for example, following code:
Copy code
@PreviewDynamicColors
@Composable
fun test() {
  AppTheme(useDynamicTheme = true) {
    Surface(
    ) {
      Box(
        modifier = Modifier
          .padding(16.dp)
          .size(20.dp)
          .background(color = MaterialTheme.colorScheme.primary),
      )
    }
  }
}
With theme:
Copy code
@Composable
fun AppTheme(
  useDynamicTheme: Boolean = true,
  useDarkTheme: Boolean = isSystemInDarkTheme(),
  content: @Composable () -> Unit
) {
  val colorScheme = when {
    useDynamicTheme -> {
      val context = LocalContext.current
      if (useDarkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
    }

    useDarkTheme -> DarkColors
    else -> LightColors
  }

  MaterialTheme(
    colorScheme = colorScheme,
    content = content
  )
}
Generates the following preview:
🧵 1
Captura de pantalla 2024-03-13 a las 20.40.35.png
s

Shahzad Ansari

03/15/2024, 10:59 PM
@alorma I faced a similar issue recently. I don't remember exactly what the issue was but something was wrong with Previews for API 34. And since that is being used as default by
@PreviewDynamicColors
, Previews weren't working as expected. I ended up writing a custom annotation class (includes Light, Dark and Dynamic color variants).
Copy code
@Preview(apiLevel = 33, uiMode = Configuration.UI_MODE_NIGHT_NO or Configuration.UI_MODE_TYPE_NORMAL, name = "Light")
@Preview(apiLevel = 33, uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, name = "Dark")
@Preview(apiLevel = 33, wallpaper = Wallpapers.GREEN_DOMINATED_EXAMPLE, name = "Green")
@Preview(apiLevel = 33, wallpaper = Wallpapers.RED_DOMINATED_EXAMPLE, name = "Red")
@Preview(apiLevel = 33, wallpaper = Wallpapers.YELLOW_DOMINATED_EXAMPLE, name = "Yellow")
@Preview(apiLevel = 33, wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE, name = "Blue")
annotation class Previews
a

alorma

03/18/2024, 7:22 AM
Thanks @Shahzad Ansari! It works like a charm
🤝 1
s

Stylianos Gakis

03/18/2024, 7:56 AM
Looks like a serious bug, have you filed a report for this?