使用 Material design 3 时如何定义 Jetpack compose 中按钮的形状

nay*_*rde 5 android android-jetpack-compose material3

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

默认情况下,按钮形状的圆角半径为 full 类型,即 20dp。根据文档。 https://m3.material.io/components/buttons/overview

如果我查看形状文档,我可以在令牌部分看到以下形状 在此输入图像描述

但是,当我向应用程序的主题提供 Shapes 对象时。我没有自定义完整形状的选项。

这是我的代码

Shapes(
    extraSmall = RoundedCornerShape(4.dp),
    small = RoundedCornerShape(8.dp),
    medium = RoundedCornerShape(12.dp),
    large = RoundedCornerShape(16.dp),
    extraLarge = RoundedCornerShape(8.dp)
)
Run Code Online (Sandbox Code Playgroud)

我想要实现的目标:

  1. 我不想为每个按钮显式指定形状或为按钮创建可组合项,然后在任何地方重复使用它。

我想应用它一次,不需要像其他组件一样显式指定它

Jan*_*ína 7

正如您所提到的,M3FilledButton的容器形状是默认的ShapeKeyTokens.CornerFull,如您在 中看到的FilledButtonTokens。然后将该标记转换为Shape函数Shapes.fromToken

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
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,ShapeKeyTokens.CornerFull与大多数其他主题不同,它不会Shape从主题转换为某些内容,而只是转换为CircleShape. 这意味着不可能做你想做的事。您必须将形状传递给每个按钮或创建自定义按钮可组合项。