欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android Jetpack Compose - Button

程序员文章站 2022-03-04 22:54:22
...

简单示例

@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 轮廓样式

Android Jetpack Compose - Button

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

           }


       }


   }

}