【问题标题】:Default Style Jetpack Compose默认样式 Jetpack 组合
【发布时间】:2021-03-21 13:33:23
【问题描述】:

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

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

我想将其转换为 Jetpack Compose。

在默认撰写示例(Android Studio Canary)中,您可以看到 ui.theme 文件夹,它是 values 文件夹的模拟,但没有字符串和维度。那么如何将字符串和维度添加到这个 compose 文件夹中呢?

【问题讨论】:

  • “我想将其转换为 Jetpack Compose”——具体取决于 ButtonStyle 中的内容。 “那么我怎样才能将字符串和维度添加到这个 compose 文件夹中呢?” -- stringResource()dimensionResource() 让您分别引用字符串和维度资源,尽管我认为它们只能在可组合函数内部使用。

标签: android android-button android-jetpack-compose


【解决方案1】:

nglauber answer 中所述,您可以在主题或按钮参数中自定义形状、版式和颜色。

您还可以覆盖这些值并构建默认按钮样式。
比如:

@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")
    }
}

【讨论】:

    【解决方案2】:

    如果您查看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 文件(资源/值)并分别使用 stringResource(id)dimensionResource(id) 函数引用它们。

    【讨论】:

    • “对于文本和尺寸,您可以继续使用 XML 文件 (res/values)”。或者,我可以使用 Dp(或 Sp)和 String 创建枚举类
    • 我还是更喜欢将 XML 主要用于字符串,因为它使应用程序的国际化更容易。
    猜你喜欢
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    相关资源
    最近更新 更多