I'm using Jetpack Compose to animate a FloatingActionButton
that hides when the user scrolls down and reappears when scrolling up.
To animate the FAB
, I use AnimatedVisibility
with fadeIn
/fadeOut
and scaleIn
/scaleOut
transitions.
Here’s the composable I’m using:
@Composable
fun AddNewNoteFAB(
modifier: Modifier = Modifier,
isVisible: Boolean = true,
onClick: () -> Unit
) {
AnimatedVisibility(
visible = isVisible,
enter = fadeIn() + scaleIn(),
exit = fadeOut() + scaleOut()
) {
FloatingActionButton(
modifier = modifier,
onClick = onClick
) {
Icon(
Icons.Default.Add,
contentDescription = "Add new note"
)
}
}
}
FAB
hides, part of its shadow is clipped.FAB
reappears, its shadow is missing completely during the animation.I’ve attached a screen recording that shows the problem in action.
padding
around the FAB
.FAB
in a Box
with Modifier.shadow(..., clip = false)
.graphicsLayer
to animate scale and alpha manually instead of using AnimatedVisibility
.AnimatedVisibility
with AnimatedContent
.Try this,
here i have used animateSize variable that will act same as scaleIn and scaleOut. Also wrapped in a Box composable, to make to center align.The value 56 dp here is the size of a default floating action button.
@Composable
fun AddNewNoteFAB(
modifier: Modifier = Modifier,
isVisible: Boolean = true,
onClick: () -> Unit
) {
val animateSize by animateDpAsState(
targetValue = if (isVisible) 56.dp else 0.dp,
animationSpec = tween(durationMillis = 100),
label = "FAB Elevation"
)
Box(Modifier.size(56.dp)){
FloatingActionButton(
modifier = modifier.align(Alignment.Center).size(animateSize),
onClick = onClick
) {
Icon(
Icons.Default.Add,
contentDescription = "Add new note"
)
}
}
}