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

Viewed 930

I'm using the clickable modifier on Surface and want to create a custom indication to have the surface (along with its contents) appear with 0.5 alpha when being pressed. But it seems the indication can only be used to draw additional UI.

How do I redraw the Surface with 0.5 alpha when it is pressed?

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

    ...

}
3 Answers

With 1.0.x in the clickable modifier you can specify the Indication parameter. You can use the default ripple defined by rememberRipple changing the color.

Something like:

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){
     //...
}

Otherwise you can use something like:

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)
) {
   //....
}

Try this:

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 )
            ) {

        }
}
Related