简单示例
@Composable
fun Button(
text: String,
modifier: Modifier = Modifier.None,
onClick: (() -> Unit)? = null,
style: ButtonStyle = ContainedButtonStyle()
) {
Button(modifier = modifier, style = style, onClick = onClick) {
Text(text = text)
}
}
例如:
@Preview
@Composable
fun buttonLayout() {
Button(text = "点击",
onClick = {
// 处理点击事件
}
)
}
或者传入可组合children来代替text属性
@Composable
fun Button(
modifier: Modifier = Modifier.None,
onClick: (() -> Unit)? = null,
style: ButtonStyle = ContainedButtonStyle(),
children: @Composable() () -> Unit
)
例如:
@Preview
@Composable
fun btLayout(){
Button(
onClick = {
// 处理点击事件
},children = {
Text(text = "点击")
}
)
}
按钮样式
- ContainedButtonStyle 默认样式
- TextButtonStyle 文本样式
- OutlinedButtonStyle 轮廓样式
@Preview
@Composable
fun btLayout() {
MaterialTheme {
Column(
) {
TopAppBar(title = { Text("Compose演示") })
val (text, setText) = state {
"点击"
}
Container(
width = Dp(200.0f),
height = Dp(40.0f)
) {
Button(
onClick = {
// 处理点击事件x
setText("TextButtonStyle")
//文字按钮
}, children = {
Text(text = text)
}, style = TextButtonStyle(contentColor = Color.Magenta)
)
}
Container(
width = Dp(200.0f),
height = Dp(40.0f)
) {
Button(
onClick = {
}, children = {
Text(text = "ContainedButtonStyle")
}, style = ContainedButtonStyle(
backgroundColor = Color.Cyan,
contentColor = Color.DarkGray,
// 圆角
shape = RoundedCornerShape(8.dp),
elevation = Dp(4f)
)
)
}
Container(
width = Dp(200.0f),
height = Dp(40.0f)
) {
Button(
onClick = {
}, children = {
Text(text = "ContainedButtonStyle")
}, style = OutlinedButtonStyle(
backgroundColor = Color.Black,
contentColor = Color.Cyan,
// 边框颜色
borderBrush = SolidColor(Color.Red),
// 边款宽度
borderWidth = Dp(4f),
elevation = Dp(4f)
)
)
}
}
}
}