前言
此篇博客讲解Button按钮
一个简单的例子
快速了解一下
效果图
代码
@Composable
fun APage() {
Column(
Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Button(onClick = {
//点击回调
Toast.makeText(this@DemoActivity, "点击按钮", Toast.LENGTH_SHORT).show()
}) {
//单单一个Button是没有内容的,这里需要在Button里添加一个Text
Text(text = "点击")
}
}
}
参数详解
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun Button(
onClick: () -> Unit, //点击回调
modifier: Modifier = Modifier,//修饰符
enabled: Boolean = true, //是否启用点击
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, //交互状态信息(用来实现选中效果、按下效果等等)
elevation: ButtonElevation? = ButtonDefaults.elevation(), //阴影效果
shape: Shape = MaterialTheme.shapes.small, //自定义形状
border: BorderStroke? = null, //按键边框
colors: ButtonColors = ButtonDefaults.buttonColors(), //背景色
contentPadding: PaddingValues = ButtonDefaults.ContentPadding, //内边距
content: @Composable RowScope.() -> Unit //Button这个父类容器的内容,注意它是横向的
)
设置按键启用状态与按键背景颜色
效果图
代码
@Composable
fun APage() {
//启用状态
val isEnabled = remember {
mutableStateOf(true)
}
//按键颜色
val buttonColors = ButtonDefaults.buttonColors(
backgroundColor = Color.Red, //背景颜色
contentColor = Color.Yellow, //内容颜色
disabledBackgroundColor = Color.DarkGray, //未启用按键背景色
disabledContentColor = Color.Black //未启用按键内容色
)
Column(
Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Button(onClick = {
Toast.makeText(this@DemoActivity, "点击", Toast.LENGTH_SHORT).show()
}, enabled = isEnabled.value, colors = buttonColors) {
Text(text = "点击")
}
Button(onClick = { isEnabled.value = !isEnabled.value }) {
Text(text = "设置上面的按键是否启用")
}
}
}
按键状态(按下效果实现)
效果图
代码
@Composable
fun APage() {
//点击状态来源
val interactionSource = remember { MutableInteractionSource() }
//interactionSource.collectIsPressedAsState() 为按下状态
//interactionSource.collectIsFocusedAsState() 为焦点选中状态
//interactionSource.collectIsHoveredAsState() 为鼠标悬停状态
//interactionSource.collectIsDraggedAsState() 为拖动状态
val buttonColors = if (interactionSource.collectIsPressedAsState().value) {
ButtonDefaults.buttonColors(
backgroundColor = Color.Gray, //背景颜色
contentColor = Color.White, //内容颜色
)
} else {
ButtonDefaults.buttonColors(
backgroundColor = Color.Cyan, //背景颜色
contentColor = Color.Black, //内容颜色
)
}
Column(
Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Button(onClick = {
Toast.makeText(this@DemoActivity, "点击", Toast.LENGTH_SHORT).show()
}, colors = buttonColors, interactionSource = interactionSource) {
Text(text = "点击")
}
}
}
end
标签:Compose,buttonColors,Color,Jetpack,Button,点击,按键,Android,interactionSource From: https://www.cnblogs.com/guanxinjing/p/17603239.html