Ben Cox
Ben Cox

Reputation: 1483

Can't animate FAB visible in M3 Scaffold

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 issue

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:

enter image description here

Workarounds I've attempted

If I do any of the following, the FAB will toggle:

  1. Put the FAB in another area, such as the Scaffold content or topbar area.
  2. Remove the AnimatedVisibility.
  3. Put the FAB inside an explicitly-sized 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:

enter image description here

What should I do to get the FAB entering and exiting as expected?

Upvotes: 8

Views: 2063

Answers (1)

Abhimanyu
Abhimanyu

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

Related Questions