I saw similar questions with no great solutions so I thought this might be useful.
I had a problem when I wanted to animate a button the user clicked to make it larger when pressed; not as easy as it sounds because when you get the animation working the onClick event never fires. [Because it depends on the up event I guess]
I found a way to make both the animation and the click work for a icon button and I thought it might work for other cases.
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun RoundIconButton(
modifier: Modifier = Modifier,
imageVector: ImageVector,
onClick: () -> Unit,
tint: Color = Color.Black.copy(alpha = 0.8f),
backgroundColor: Color =
MaterialTheme.colors.background,
elevation: Dp = 4.dp,
contentDescription: String
) {
val interactionSource = remember {
MutableInteractionSource() }
val isPressed by
interactionSource.collectIsPressedAsState()
val transition = updateTransition(targetState
= isPressed, label = "")
val size by transition.animateDp(label = "")
{ state ->
when(state) {
false -> 40.dp
true -> 50.dp
}
}
Card(
modifier = modifier
.padding(all = 4.dp)
.clickable(interactionSource =
interactionSource,indication =
LocalIndication.current,onClick= onClick)
.then(Modifier.size(size)),
shape = CircleShape,
backgroundColor = backgroundColor,
elevation = elevation,
) {
Icon( imageVector = imageVector,
contentDescription = contentDescription,tint
= tint)
}
}