默认样式 Jetpack Compose

4

有人知道如何将默认样式更改为按钮样式吗? XML中的样式:

<item name="materialButtonStyle">@style/ButtonStyle</item>

我希望将其转换为Jetpack Compose。

在默认的Compose样本(Android Studio Canary)中,您可以看到ui.theme文件夹,它类似于values文件夹,但没有Strings和Dimens。那么我该如何将Strings和Dimens添加到这个compose文件夹中?


“我想将它转换为Jetpack Compose” - 具体细节取决于ButtonStyle中的内容。 “那么我该如何将字符串和尺寸添加到这个compose文件夹中?” - stringResource()dimensionResource()让您分别引用字符串和尺寸资源,但我认为它们仅在可组合函数内部可用。 - CommonsWare
2个回答

3
正如nglauber答案所述,您可以自定义主题中的形状、字体和颜色,或在按钮参数中进行设置。
此外,您还可以覆盖这些值并构建默认按钮样式。
像这样:
@Composable
fun DefaultButtonStyle(content: @Composable () -> Unit) {
    MaterialTheme(
        //override the shape
        shapes = MaterialTheme.shapes.copy(small = CutCornerShape(12.dp)),
        //Override the typography.button using the merge method
        typography = MaterialTheme.typography.copy(
            button = MaterialTheme.typography.button.merge(TextStyle(fontSize = 20.sp))),
        //override the colors define in the material theme
        colors = MaterialTheme.colors.copy(
            primary = Color.Yellow,
            onPrimary = Color.Blue)
    ) {
        content()
    }
}

接下来只需使用它:

DefaultButtonStyle() {
    Button(onClick = { /*....*/ }) {
        Text(text = "BUTTON")
    }
}

0

如果你查看 Button 的源代码,你会注意到它使用了一些默认值,你可以通过参数或自定义样式来进行定制。

  • shape: 使用了 MaterialTheme.shapes.small(你可以在自己的样式中自定义这个字段);
val shapes = Shapes(
    small = CutCornerShape(4.dp), // << here
    medium = RoundedCornerShape(4.dp),
    large = RoundedCornerShape(0.dp)
)
  • colors:是ButtonColors的一个实例,提供了backgroundColorcontentColordisabledBackgroundColordisabledContentColor。请查看Button.buttonColors函数以了解如何自定义按钮的颜色。

  • 在文本方面,Button组件从MaterialTheme.typography.button获取文本样式,因此您可以在样式中覆盖此字段以自定义按钮的文本。

val typography = Typography(
    ...
    button = defaultTypography.button.copy(
        fontFamily = yourFontFamily, 
        color = Color.Yellow
    )
)

对于文本和尺寸,您可以继续使用 XML 文件(res/values)并分别使用 stringResource(id)dimensionResource(id) 函数引用它们。


对于文本和尺寸,您可以继续使用XML文件(res/values)。或者,我可以创建带有Dp(或Sp)和String的枚举类。 - Renattele Renattele
我仍然更喜欢主要使用XML来处理字符串,因为这使得应用程序的国际化更加容易。 - nglauber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接