[英]How to make Jetpack Compose theme customizable?
我正在使用 Jetpack Compose 開發一個設計系統,我有很多組件都使用我的主題來訪問 colors、排版和尺寸。 現在我正在研究允許定制的可能性。 例如,覆蓋顏色會導致每個組件發生變化。
到目前為止,我嘗試將參數添加到有趣的 MyTheme 中,我已經通過這種方法取得了一些成功,但問題是任何開發人員都可以像這樣隨時修改主題。 我希望它只能定制一次,比如 singleton。有什么想法或建議嗎?
這是我的主題:
private val LightColorPalette = LightColors()
private val DarkColorPalette = DarkColors()
private val LocalColors = compositionLocalOf<MyColors> {
error("No typography provided! Make sure to wrap all usages of this components in a MyTheme.")
}
private val LocalTypography = compositionLocalOf<MyTypography> {
error("No typography provided! Make sure to wrap all usages of this components in a MyTheme.")
}
private val LocalDimensions = staticCompositionLocalOf { MyDimensions() }
@Composable
fun MyTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
colors: MyColors = if (darkTheme) DarkColorPalette else LightColorPalette,
typography: MyTypography = getTypography(LocalConfiguration.current),
dimensions: MyDimensions = getDimensions(LocalConfiguration.current),
content: @Composable () -> Unit
) {
val shapes = MaterialShapes
CompositionLocalProvider(
LocalTypography provides typography,
LocalColors provides colors,
LocalDimensions provides dimensions,
) {
MaterialTheme(
colors = debugColors(darkTheme),
content = content,
shapes = shapes
)
}
}
我設法通過公開所有CompositionLocal變量來實現這一點。 有了這個,任何使用CompositionLocalProvider覆蓋此變量的新主題都將在其下使用此新值的可組合項。
@Composable
fun SecondaryTheme(
content: @Composable () -> Unit
) {
val configuration = LocalConfiguration.current
val colors = SecondaryColors()
val typography = getDefaultTypography(configuration)
val dimensions = getDefaultDimensions(configuration)
val shapes = MaterialShapes
CompositionLocalProvider(
LocalTypography provides typography,
LocalColors provides colors,
LocalDimensions provides dimensions,
) {
MaterialTheme(
colors = materialColors(darkTheme),
content = content,
shapes = shapes
)
}
}
我建議查看官方文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.