Jetpack Compose 添加自定义深色/浅色?

Coo*_*ter 5 android material-components-android android-jetpack-compose

如果可以创建深色和浅色调色板,那就可以了。 在此输入图像描述

但它只有12种颜色。如何为浅色和深色调色板添加更多自定义颜色?

Tha*_*oro 33

你可以用CompositionLocalProvider它。

  1. 创建一个数据类,其中包含您要使用的内容及其staticCompositionLocalOf. 例如CustomColorsPalette.kt
@Immutable
data class CustomColorsPalette(
    val custom1OnBackground: Color = Color.Unspecified,
    val custom2OnBackground: Color = Color.Unspecified,
    val custom1OnSurface: Color = Color.Unspecified,
    val custom2OnSurface: Color = Color.Unspecified,
    val other1: Color = Color.Unspecified,
    val other2: Color = Color.Unspecified
)

val LocalCustomColorsPalette = staticCompositionLocalOf { CustomColorsPalette() }
Run Code Online (Sandbox Code Playgroud)
  1. 根据浅色或深色主题创建不同的变体:
val OnLightCustomColorsPalette = CustomColorsPalette(
    custom1OnBackground = Color(color = 0xFF1A237E),
    custom2OnBackground = Color(color = 0xFF1B5E20),
    custom1OnSurface = Color(color = 0xFFE53935),
    custom2OnSurface = Color(color = 0xFFD81B60),
    other1 = Color(color = 0xFF006064),
    other2 = Color(color = 0xFF643700)
)

val OnDarkCustomColorsPalette = CustomColorsPalette(
    custom1OnBackground = Color(color = 0xFF1E88E5),
    custom2OnBackground = Color(color = 0xFF43A047),
    custom1OnSurface = Color(color = 0xFFC62828),
    custom2OnSurface = Color(color = 0xFFAD1457),
    other1 = Color(color = 0xFF00897B),
    other2 = Color(color = 0xFF896200)
)
Run Code Online (Sandbox Code Playgroud)
  1. 使用主题中的逻辑Compose来决定何时使用其中之一:
@Composable
fun AppTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit
) {
    val colors = if (darkTheme) DarkColorPalette else LightColorPalette
    
    val customColorsPalette =
        if (darkTheme) OnDarkCustomColorsPalette
        else OnLightCustomColorsPalette

    CompositionLocalProvider(
        LocalCustomColorsPalette provides customColorsPalette
    ) {
        MaterialTheme(
            colors = colors,
            typography = Typography,
            shapes = Shapes,
            content = content
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

现在可以直接从可组合代码中使用这些颜色LocalCustomColorsPalette.current

Text(
    text = "Anything...",
    color = LocalCustomColorsPalette.current.custom1OnBackground
)
Run Code Online (Sandbox Code Playgroud)

CompositionLocalProvider有关文档的更多信息。


奖金

可以更改对 的调用,LocalCustomColorsPalette.current使其与我们对 的其他属性的调用类似MaterialTheme。为此,您可以添加以下代码(它可以与第一步位于同一文件中):

// ...

val MaterialTheme.customColorsPalette: CustomColorsPalette
    @Composable
    @ReadOnlyComposable
    get() = LocalCustomColorsPalette.current
Run Code Online (Sandbox Code Playgroud)

现在你可以这样使用:

Text(
    text = "Anything...",
    color = MaterialTheme.customColorsPalette.custom1OnBackground
)
Run Code Online (Sandbox Code Playgroud)

  • 你好。我正在尝试遵循您的解决方案,但 MaterialTheme( 颜色 = 颜色,此颜色给我一个错误,需要颜色并找到 CustomColorsPalette (2认同)