一、背景
? ? ? ? 在使用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 = trueonClick()} 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)}}})
}
????????