[英]Jetpack Compose - Cannot change the default font in Material 3
[英]Default Style Jetpack Compose
有人知道如何將默認樣式更改為按鈕嗎? xml 中的樣式:
<item name="materialButtonStyle">@style/ButtonStyle</item>
我想將其轉換為 Jetpack Compose。
在默認撰寫示例(Android Studio Canary)中,您可以看到 ui.theme 文件夾,它是 values 文件夾的模擬,但沒有字符串和維度。 那么如何將字符串和維度添加到這個 compose 文件夾中呢?
如nglauber 答案中所述,您可以在主題或 Button 參數中自定義形狀、版式和顏色。
您也可以覆蓋這些值並構建默認按鈕樣式。
就像是:
@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")
}
}
如果您查看Button
源代碼,您會注意到它使用了幾個您可以自定義的默認值(通過參數或自定義樣式)。
shape
:使用MaterialTheme.shapes.small
(您可以根據自己的風格自定義此字段);val shapes = Shapes(
small = CutCornerShape(4.dp), // << here
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
)
colors
:它是ButtonColors
的一個實例,它提供了backgroundColor
、 contentColor
、 disabledBackgroundColor
和disabledContentColor
。 查看Button.buttonColors
function 以了解如何為您的按鈕自定義 colors。
在文本方面, Button
組件從MaterialTheme.typography.button
獲取文本樣式,因此您可以在樣式中覆蓋此字段以自定義按鈕的文本。
val typography = Typography(
...
button = defaultTypography.button.copy(
fontFamily = yourFontFamily,
color = Color.Yellow
)
)
對於文本和尺寸,您可以繼續使用 XML 文件(res/values)並分別使用stringResource(id)
和dimensionResource(id)
函數引用它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.