一、背景
在使用Compose实现Button按钮时,设计要求移除按钮的水波纹效果,只保留按压效果,经查Compose1.4.3版本中,并没有直接移除水波纹的能力
二、遇到问题
经过多次尝试,使用Compose的Button组件始终无法实现目标效果,使用Box+Text 最终绘制的效果Text显示的颜色和字间距又和Button效果渲染的不一致,
三、效果演示
这里就不演示了。代码在下面,你试试就知道效果了
三、实现方案
经过多次失败后,看了一下Compose的Button组件源码,找到问题所在。最终得出以下效果实现代码
@Composable
fun ButtonBlackOutline(modifier: Modifier = Modifier, content: String, onClick: () -> Unit) {
var isPressed by remember { mutableStateOf(false) }
var buttonRect by remember { mutableStateOf(Rect.Zero) }
Box(
modifier = modifier
.background(
color = if (isPressed) colorResource(id = CommonColor.common_pressed_btn_color) else colorResource(id = CommonColor.color_transparent),
shape = RoundedCornerShape(100.dp)
)
.fillMaxWidth()
.height(40.dp)
.border(0.5.dp, colorResource(id = CommonColor.text_600), RoundedCornerShape(100.dp))
.pointerInteropFilter {
when (it.action) {
MotionEvent.ACTION_DOWN -> {
isPressed = true
}
MotionEvent.ACTION_UP -> {
if (buttonRect.contains(offset = Offset(it.x, it.y))) {
isPressed = true
onClick()
} else {
isPressed = false
}
}
MotionEvent.ACTION_CANCEL -> {
isPressed = false
}
MotionEvent.ACTION_MOVE -> {
if (buttonRect.contains(offset = Offset(it.x, it.y))) {
isPressed = true
} else {
isPressed = false
}
}
}
true
}
.onGloballyPositioned { coordinates ->
buttonRect = Rect(
offset = coordinates.positionInWindow(),
size = coordinates.size.toSize()
)
},
contentAlignment = Alignment.Center,
content = {
// 实现和Button效果一致的重要代码
CompositionLocalProvider(
LocalContentAlpha provides ButtonDefaults.buttonColors().contentColor(enabled = true).value.alpha
) {
ProvideTextStyle(
value = MaterialTheme.typography.button
) {
Text(
text = content
)
}
}
}
)
}