簡體   English   中英

使用 Material Design 3 時如何在 Jetpack Compose 中定義按鈕的形狀

[英]How to define shape for Button in Jetpack compose when using Material design 3

我正在使用 Material design 3 和 Jetpack compose。

默認情況下,Button 的 Shape 的角半徑類型為 full,為 20dp。 根據文檔。 https://m3.material.io/components/buttons/overview

如果查看形狀文檔,我可以在令牌部分看到以下形狀在此處輸入圖像描述

但是,當我向應用程序的主題提供形狀 object 時。 我沒有自定義 Full Shape 的選項。

這是我的代碼

Shapes(
    extraSmall = RoundedCornerShape(4.dp),
    small = RoundedCornerShape(8.dp),
    medium = RoundedCornerShape(12.dp),
    large = RoundedCornerShape(16.dp),
    extraLarge = RoundedCornerShape(8.dp)
)

我想要實現的目標:

  1. 我不想為每個按鈕明確指定形狀或為按鈕創建一個可組合項,然后在任何地方重復使用它。

我想應用一次,不需要像其他組件一樣明確指定

正如您提到的,M3 FilledButton的容器形狀默認為ShapeKeyTokens.CornerFull ,如您在FilledButtonTokens中所見。 這個標記然后在Shapes.fromToken function 中轉換為Shape

internal fun Shapes.fromToken(value: ShapeKeyTokens): Shape {
    return when (value) {
        ShapeKeyTokens.CornerExtraLarge -> extraLarge
        ShapeKeyTokens.CornerExtraLargeTop -> extraLarge.top()
        ShapeKeyTokens.CornerExtraSmall -> extraSmall
        ShapeKeyTokens.CornerExtraSmallTop -> extraSmall.top()
        ShapeKeyTokens.CornerFull -> CircleShape
        ShapeKeyTokens.CornerLarge -> large
        ShapeKeyTokens.CornerLargeEnd -> large.end()
        ShapeKeyTokens.CornerLargeTop -> large.top()
        ShapeKeyTokens.CornerMedium -> medium
        ShapeKeyTokens.CornerNone -> RectangleShape
        ShapeKeyTokens.CornerSmall -> small
    }
}

如您所見,與大多數其他人不同, ShapeKeyTokens.CornerFull並未從主題轉換為某些Shape ,而只是轉換為CircleShape 這意味着不可能做你想做的事。 您要么必須將形狀傳遞給每個按鈕,要么創建自定義按鈕可組合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM