Arjun Achatz
11/09/2021, 5:19 PMLouis Pullen-Freilich [G]
11/09/2021, 5:46 PMcollectIsPressedAsState
will not change if the press / release happens within the same frame / composition - as any changes that respond to this would then be shown after the press had already stopped. Ripples are different because they are launched in response to a press and can last longer than the press itself. You can manually observe the flow inside if you want something similarArjun Achatz
11/09/2021, 6:55 PMval clickFlow = remember { MutableSharedFlow<ButtonClickState>() }
val isClickPressed = clickFlow.collectAsState(initial = ButtonClickState.Released).value == ButtonClickState.Pressed
val backgroundColor =
if (isClickPressed && state == ButtonState.Enabled) {
pressedBackgroundColor
} else {
if (isDarkTheme) defaultBackgroundDarkColor else defaultBackgroundLightColor
}
androidx.compose.material.Button(
onClick = { onClick.takeIf { state == ButtonState.Enabled }?.invoke() },
modifier = modifier
.requiredHeightIn(min = 48.dp)
.pointerInput(Unit) {
this.detectTapGestures(
onPress = {
clickFlow.emit(ButtonClickState.Pressed)
awaitRelease()
clickFlow.emit(ButtonClickState.Released)
}
)
},
Arjun Achatz
11/09/2021, 6:55 PMLouis Pullen-Freilich [G]
11/09/2021, 7:02 PMInteractionSource.interactions
LaunchedEffect(interactionSource) {
interactionSource.interactions.collect { interaction ->
when (interaction) {
is PressInteraction.Press -> /* do something*
...
Arjun Achatz
11/09/2021, 7:20 PMArjun Achatz
11/09/2021, 7:20 PMLouis Pullen-Freilich [G]
11/09/2021, 7:22 PMmutableState
as with collectIsPressedAsState
though - if you change it within a composition, the updates will be batched and ignored. So you’ll need to launch an animation if you want a pressed effect to show for longer than the tapArjun Achatz
11/09/2021, 9:39 PMcollectIsPressedAsState
doesArjun Achatz
11/09/2021, 9:40 PMLouis Pullen-Freilich [G]
11/09/2021, 9:41 PMArjun Achatz
11/09/2021, 9:44 PMArjun Achatz
11/09/2021, 9:45 PMArjun Achatz
11/10/2021, 3:08 AMArjun Achatz
11/10/2021, 3:08 AMArjun Achatz
11/10/2021, 3:08 AMsetContent {
val interactionSource = remember { MutableInteractionSource() }
var backgroundColor by remember { mutableStateOf(Color.Red) }
LaunchedEffect(interactionSource) {
interactionSource.interactions.collect { interaction ->
when (interaction) {
is PressInteraction -> {
backgroundColor = when (interaction) {
is PressInteraction.Press -> Color.Blue
else -> {
delay(500L)
Color.Red
}
}
}
}
}
}
ButtonStatesTheme {
Surface {
Box(Modifier.fillMaxSize(), Alignment.Center) {
Button(
colors = ButtonDefaults.buttonColors(backgroundColor = backgroundColor),
onClick = { /*TODO*/ },
content = { Text("Clicked") },
interactionSource = interactionSource,
)
}
}
}
}