按下 Compose Surface 时更改 alpha(可点击修饰符)

Change alpha when Compose Surface is being pressed (clickable modifier)

我在 Surface 上使用 clickable 修饰符,并希望创建一个自定义指示,使表面(及其内容)在按下时以 0.5 alpha 显示。不过这个指示好像只能用来画额外的UI.

如何在按下 Surface 时使用 0.5 alpha 重绘它?

Surface(
   modifier = Modifier.clickable(interactionSource = remember { MutableInteractionSource() }, indication = CustomIndication, onClick = onClick)
    ) {

    ...

}

试试这个:

var isPressed by remember { mutableStateOf(false) }
val backgroundAlpha = if (isPressed) 0.5f else 1f
Surface(
    modifier = Modifier
        .clickable {  }
        .pointerInput(Unit) {
            detectTapGestures(
                onPress = {
                    isPressed = true
                    val success = tryAwaitRelease()
                    if (success) isPressed = false
                    else isPressed = true
                }
            )
        },
    color = MaterialTheme.colors.primary.copy(alpha = backgroundAlpha)
) {
    ...
}
@Composable
fun AlphaSurface(){
    val isClicked = remember { mutableStateOf(false) }
    val alphaValue = if(isClicked.value) 0.5f else 1f
        Surface(
            modifier = Modifier.clickable {
                isClicked.value = isClicked.value.not() // toggle the value 
            }.fillMaxHeight().fillMaxWidth(),
            color = MaterialTheme.colors.primary.copy(alpha = alphaValue )
            ) {

        }
}

clickable 修饰符中使用 1.0.x 您可以指定 Indication parameter. You can use the default ripple defined by rememberRipple 更改颜色。

类似于:

val interactionSource = remember { MutableInteractionSource() }

//clickable modifier
val clickable = Modifier.clickable(
    interactionSource = interactionSource,
    indication = rememberRipple(color = /* use you custom color */
       MaterialTheme.colors.primary.copy(alpha = 0.5f))
) { /* update some business state here */ }


Surface(modifier = clickable){
     //...
}

否则你可以使用类似的东西:

val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val backgroundAlpha = if (isPressed) 0.5f else 1f

Surface(
    modifier = Modifier.clickable(true){},
    color= MaterialTheme.colors.secondary.copy(alpha = backgroundAlpha)
) {
   //....
}