You can use the AnimatedVisibility component in Jetpack Compose to animate the transformation of your FAB to a DropdownMenu. Here's an example:
@Composable
fun FABWithDropDownMenu() {
var expanded by remember { mutableStateOf(false) }
val items = listOf("Option 1", "Option 2", "Option 3")
val dropDownHeight = with(DensityAmbient.current) { items.size * 48.dp.toPx() }
Box {
FloatingActionButton(
onClick = { expanded = !expanded },
shape = CircleShape,
backgroundColor = MaterialTheme.colors.primary
) {
Icon(Icons.Default.ArrowDropDown, contentDescription = null)
}
AnimatedVisibility(
visible = expanded,
enter = slideInVertically(
initialOffsetY = { -dropDownHeight },
animationSpec = tween(durationMillis = 300)
),
exit = slideOutVertically(
targetOffsetY = { -dropDownHeight },
animationSpec = tween(durationMillis = 300)
)
) {
DropdownMenu(
modifier = Modifier.fillMaxWidth(),
expanded = expanded,
onDismissRequest = { expanded = false }
) {
items.forEachIndexed { index, string ->
DropdownMenuItem(onClick = { expanded = false }) {
Text(text = string)
}
}
}
}
}
}
In this example, we first create a Box composable to contain both the FloatingActionButton and the AnimatedVisibility component. The expanded variable is used to track whether the dropdown menu is expanded or not, and the items list contains the options to display in the menu.
In the FloatingActionButton click listener, we toggle the value of expanded.
Next, we use the AnimatedVisibility component to animate the transformation of the FAB into the dropdown menu. We specify visible = expanded to animate the enter and exit transitions when the menu is expanded and collapsed.
For the enter transition, we use the slideInVertically animation with an initial offset that starts at -dropDownHeight and moves upward to 0. We also specify a tween animation spec with a duration of 300 milliseconds.
For the exit transition, we use the slideOutVertically animation with a target offset that starts at 0 and moves upward to -dropDownHeight. We again use a tween animation spec with a duration of 300 milliseconds.
Finally, we create the DropdownMenu composable inside the AnimatedVisibility component. The expanded parameter is set to expanded so that the menu expands when expanded is true and collapses when expanded is false. The onDismissRequest parameter is used to collapse the menu when the user clicks outside of the menu.
Inside the DropdownMenu, we use a forEachIndexed loop to create a DropdownMenuItem for each item in the items list. The onClick parameter of the DropdownMenuItem is set to collapse the menu when the user clicks on an item.