在我的android项目中,我正在做一个简单的浮动动作按钮,可以展开并显示按钮列表来执行不同的动作。为了跟踪FAB的当前状态,我有下一个enum类
enum class FabState {
Expanded,
Collapsed
}
显示浮动动作按钮,我有以下可组合函数:
@Composable
fun MultiFloatingActionButton(
icon: ImageVector,
iconTint: Color = Color.White,
miniFabItems: List<MinFabItem>,
fabState: FabState, //The initial state of the FAB
onFabStateChanged: (FabState) -> Unit,
onItemClick: (MinFabItem) -> Unit
) {
val transition = updateTransition(targetState = fabState, label = "transition")
val rotate by transition.animateFloat(label = "rotate") {
when (it) {
FabState.Collapsed -> 0f
FabState.Expanded -> 315f
}
}
val fabScale by transition.animateFloat(label = "fabScale") {
when (it) {
FabState.Collapsed -> 0f
FabState.Expanded -> 1f
}
}
val alpha by transition.animateFloat(label = "alpha") {
when (it) {
FabState.Collapsed -> 0f
FabState.Expanded -> 1f
}
}
val shadow by transition.animateDp(label = "shadow", transitionSpec = { tween(50) }) { state ->
when (state) {
FabState.Expanded -> 2.dp
FabState.Collapsed -> 0.dp
}
}
Column(
horizontalAlignment = Alignment.End
) { // This is where I have my question, in the if condition
if (fabState == FabState.Expanded || transition.currentState == FabState.Expanded) {
miniFabItems.forEach { minFabItem ->
MinFab( //Composable for creating sub action buttons
fabItem = minFabItem,
alpha = alpha,
textShadow = shadow,
fabScale = fabScale,
onMinFabItemClick = {
onItemClick(minFabItem)
}
)
Spacer(modifier = Modifier.size(16.dp))
}
}
FloatingActionButton(
onClick = {
onFabStateChanged(
when (fabState) {
FabState.Expanded -> {
FabState.Collapsed
}
FabState.Collapsed -> {
FabState.Expanded
}
}
)
}
) {
Icon(
imageVector = icon,
tint = iconTint,
contentDescription = null,
modifier = Modifier.rotate(rotate)
)
}
}
}
我定义的常量是用于根据FAB状态显示/隐藏按钮的动画。
当我第一次创建函数时,原始条件给了我不同的行为,并且尝试了所有可能的条件,我得到了3个不同的结果:
- 条件1:
if (transition.currentState == FabState.Expanded) {...}
结果:动画不是从折叠加载到展开,而是从展开加载到折叠
- 第二个条件:
if (fabState == FabState.Expanded) {...}
结果:动画从折叠加载到展开,而不是从展开加载到折叠
第三个条件(我现在使用的条件):if (fabState == FabState.Expanded || transition.currentState == FabState.Expanded) {...}
结果:动画以两种方式加载
所以我的问题是:每个条件如何改变动画的行为?
任何帮助都会很感激。提前感谢
fabState
在onFabStateChanged
调用时更新,transition.currentState
在转换结束时更新,transition.isRunning
返回false
动画只有在可组合对象出现在树中时才会发生。当if块中的条件为false时,这些元素不能用于动画。
条件1在进入期间为假,打破了进入动画,条件2在退出期间为假,打破了退出动画,退出后两者都为假。因此,合并它们可以解决您的问题,并且还可以在不需要时从树中删除可组合内容。
更好的方法
AnimatedVisibility(
visible = fabState == FabState.Expanded,
enter = fadeIn()+ scaleIn(),
exit = fadeOut() + scaleOut(),
) {
miniFabItems.forEach { minFabItem ->
MinFab(
fabItem = minFabItem,
textShadow = 0.dp,
onMinFabItemClick = {
onItemClick(minFabItem)
}
)
Spacer(modifier = Modifier.size(16.dp))
}
}
使用graphicsLayer
修饰符to代替rotate
Icon(
imageVector = Icons.Default.Add,
tint = Color.White,
contentDescription = null,
modifier = Modifier
.graphicsLayer {
this.rotationZ = rotate
}
)