您可以使用CompositionLocalProvider
为了那个原因。
- 创建一个数据类,其中包含您要使用的内容及其
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() }
- 根据浅色或深色主题创建不同的变体:
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)
)
- 使用中的逻辑
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
)
}
}
现在可以直接从可组合代码中使用这些颜色LocalCustomColorsPalette.current
:
Text(
text = "Anything...",
color = LocalCustomColorsPalette.current.custom1OnBackground
)
有关更多信息CompositionLocalProvider
on docs.
Bonus
可以将调用更改为LocalCustomColorsPalette.current
使其与我们拥有的其他属性相似MaterialTheme
。为此,您可以添加以下代码(它可以与第一步位于同一文件中):
// ...
val MaterialTheme.customColorsPalette: CustomColorsPalette
@Composable
@ReadOnlyComposable
get() = LocalCustomColorsPalette.current
现在你可以这样使用:
Text(
text = "Anything...",
color = MaterialTheme.customColorsPalette.custom1OnBackground
)