Android Jetpack Compose - Button

簡單示例

@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)
    }
}
複製代碼

例如:bash

@Preview
@Composable
fun buttonLayout() {
    Button(text = "點擊",
        onClick = {
            // 處理點擊事件
        }
    )
}
複製代碼

或者傳入可組合children來代替text屬性markdown

@Composable
fun Button(
    modifier: Modifier = Modifier.None,
    onClick: (() -> Unit)? = null,
    style: ButtonStyle = ContainedButtonStyle(),
    children: @Composable() () -> Unit
)
複製代碼

例如:spa

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

           }


       }


   }

}
複製代碼
相關文章
相關標籤/搜索