Jetpack Compose 教學上課講義【從零開始學 Jetpack Compose 程式設計】按鈕元件
【從零開始學 Jetpack Compose 程式設計】
線上教學課程目錄: https://bit.ly/3JF4SFA
Youtube 課程播放清單:https://bit.ly/3tFjRbx
Udemy 線上課程:https://bit.ly/3MbVnhO
基本按鈕
//隸屬在 material
import androidx.compose.material.*
Button(
onClick = { Log.d("HKT", "onClick...") },
) {
Text(text = "HKT線上教室")
}
按鈕顏色
Button(
onClick = {},
colors = ButtonDefaults.textButtonColors(
backgroundColor = Color.Green,
contentColor = Color.Black
)
) {
Text("HKT線上教室",color = Color.Blue)
}
按鈕間距
Button(
onClick = {},
contentPadding = PaddingValues(
start = 20.dp,
top = 10.dp,
end = 20.dp,
bottom = 10.dp
),
modifier = Modifier.padding(50.dp)
) {
Text("HKT線上教室", fontSize = 30.sp)
}
圖案按鈕
https://fonts.google.com/icons
Button(
onClick = { /* ... */ },
contentPadding = PaddingValues(
start = 20.dp,
top = 12.dp,
end = 20.dp,
bottom = 12.dp
)
) {
Icon(
Icons.Filled.Favorite,
contentDescription = "Favorite",
modifier = Modifier.size(ButtonDefaults.IconSize)
)
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
Text("Like")
}
+1 範例
remember:記住資料
mutableStateOf: 存單一狀態值,字串、數字
var counter by remember { mutableStateOf(0) }
Column {
Text(text = "$counter")
Button(
onClick = {
counter++
}
) {
Text(text = "+1")
}
}
作業
作業解答
@Composable
fun Demo() {
// var counter = 0
var counter by remember {
mutableStateOf(0)
}
ConstraintLayout(
modifier = Modifier
.fillMaxSize()
) {
val (textCounter,
btnPlus,
btnMinus) = createRefs()
val topGuideline = createGuidelineFromTop(0.2f)
val bottomGuideline = createGuidelineFromBottom(0.2f)
Text("$counter",
fontSize = 50.sp,
modifier = Modifier.constrainAs(textCounter) {
top.linkTo(topGuideline)
start.linkTo(parent.start)
end.linkTo(parent.end)
})
Button(onClick = {
counter++
},
modifier = Modifier
.constrainAs(btnPlus) {
bottom.linkTo(bottomGuideline)
start.linkTo(parent.start)
end.linkTo(btnMinus.start)
}) {
Text("+1", fontSize = 50.sp)
}
Button(onClick = {
counter--
},
modifier = Modifier
.constrainAs(btnMinus) {
bottom.linkTo(bottomGuideline)
start.linkTo(btnPlus.end)
end.linkTo(parent.end)
}) {
Text("-1", fontSize = 50.sp)
}
}
}