我正在尝试在 Jetpack Compose 中创建一个 Material 3 浮动操作按钮,单击后该按钮会展开为具有多个选项的工作表。我正在努力实现这样的目标:
上面的例子来自Material 3网站。但是,我不知道如何实现这样的事情。我尝试在网上搜索它,但几乎所有教程都显示通过单击将一个 FAB 转换为多个其他 FAB。
我尝试修改一个
ExtendedFloatingActionButton
但没有得到我想要的结果。我还尝试使用 AnimatedContent
在正常 FloatingActionButton
和包含其他选项的多个 Column
的 Row
之间设置动画,但仍然无法获得所需的结果。
任何指导将不胜感激。预先感谢!
我让它几乎相同,你不需要这里的一切,一些参数是特定于我的代码的。可扩展基本上只是使工厂可以在多个不同的屏幕上使用,允许您选择是否扩展。如果你愿意的话,你可以去掉它,与其他参数一样。
// Custom fab that allows for displaying extended content
@Composable
fun CustomFloatingActionButton(
expandable: Boolean,
onFabClick: () -> Unit,
fabIcon: ImageVector
) {
var isExpanded by remember { mutableStateOf(false) }
if (!expandable) { // Close the expanded fab if you change to non expandable nav destination
isExpanded = false
}
val fabSize = 64.dp
val expandedFabWidth by animateDpAsState(
targetValue = if (isExpanded) 200.dp else fabSize,
animationSpec = spring(dampingRatio = 3f)
)
val expandedFabHeight by animateDpAsState(
targetValue = if (isExpanded) 58.dp else fabSize,
animationSpec = spring(dampingRatio = 3f)
)
Column {
// ExpandedBox over the FAB
Box(
modifier = Modifier
.offset(y = (25).dp)
.size(
width = expandedFabWidth,
height = (animateDpAsState(if (isExpanded) 225.dp else 0.dp, animationSpec = spring(dampingRatio = 3f))).value)
.background(
MaterialTheme.colorScheme.surfaceContainer,
shape = RoundedCornerShape(18.dp)
)
) {
// Customize the content of the expanded box as needed
}
FloatingActionButton(
onClick = {
onFabClick()
if (expandable) {
isExpanded = !isExpanded
}
},
modifier = Modifier
.width(expandedFabWidth)
.height(expandedFabHeight),
shape = RoundedCornerShape(18.dp)
) {
Icon(
imageVector = fabIcon,
contentDescription = null,
modifier = Modifier
.size(24.dp)
.offset(x = animateDpAsState(if (isExpanded) -70.dp else 0.dp, animationSpec = spring(dampingRatio = 3f)).value)
)
Text(
text = "Create Reminder",
softWrap = false,
modifier = Modifier
.offset(x = animateDpAsState(if (isExpanded) 10.dp else 80.dp, animationSpec = spring(dampingRatio = 3f)).value)
.alpha(animateFloatAsState(if (isExpanded) 1f else 0f, animationSpec = spring(dampingRatio = 3f)).value)
)
}
}
}