5

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

    ...

}
Brian Spilner
  • 581
  • 1
  • 5
  • 12

3 Answers3

7

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)
) {
   //....
}
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
1

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)
) {
    ...
}
Saurabh Thorat
  • 18,131
  • 5
  • 53
  • 70
0
@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 )
            ) {

        }
}
Muhammad Saad
  • 713
  • 1
  • 9
  • 31