Reputation: 1483
I'm trying to get behaviour where I can toggle visibility of a FAB, with a bit of entry/exit animation, in the Compose Scaffold
.
The FAB disappears fine. However, whatever I try, I can't get it to reappear - it's like it totally disappears from the tree, never to return!
This code reproduces the issue:
class TestActivity : ComponentActivity() {
@OptIn(ExperimentalMaterial3Api::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
var fabVisible by remember { mutableStateOf(true) }
Scaffold(
floatingActionButton = {
AnimatedVisibility(visible = fabVisible) {
FloatingActionButton(onClick = {}) {
Icon(Icons.Default.Star, contentDescription = null)
}
}
}
) {
Button(onClick = { fabVisible = !fabVisible }) {
Text("Click to toggle FAB")
}
}
}
}
}
Here's a demo - the FAB does a sort of wipe out, but then never returns:
If I do any of the following, the FAB will toggle:
Scaffold
content or topbar
area.AnimatedVisibility
.Box
:
…
Scaffold(
floatingActionButton = {
Box(
modifier = Modifier
.width(56.0.dp)
.height(56.0.dp)
) {
AnimatedVisibility(visible = fabVisible) {
FloatingActionButton(onClick = {}) {
Icon(Icons.Default.Star, contentDescription = null)
}
}
}
}
)
…
Obviously solutions 1 and 2 don't achieve what I want, and solution 3 (the Box
solution) isn't ideal - I have to know the size of the FAB to do this (I imagine there's probably a way to remember its intrinsic size when first visible?) and the animation is odd - it goes from the corner from the middle rather than from the centre, and the elevation suddenly 'pops' right at the end:
What should I do to get the FAB entering and exiting as expected?
Upvotes: 8
Views: 2063
Reputation: 14827
Try with scaleIn
and scaleOut
animations.
AnimatedVisibility(
visible = fabVisible,
enter = scaleIn(),
exit = scaleOut(),
) {
FloatingActionButton(onClick = {}) {
Icon(Icons.Default.Star, contentDescription = null)
}
}
Upvotes: 15