Compose 提供了丰富的动画 API,从简单的属性动画到复杂的过渡效果。本文将深入讲解动画的进阶用法。
一、Transition API
val transition = updateTransition(expanded, label = "card")
val cardHeight by transition.animateDp(label = "height") {
if (it) 300.dp else 100.dp
}
val cardColor by transition.animateColor(label = "color") { ... }
二、AnimatedContent
AnimatedContent(
targetState = count,
transitionSpec = {
slideInVertically { it } + fadeIn() togetherWith
slideOutVertically { -it } + fadeOut()
}
) { targetCount ->
Text("$targetCount")
}
三、共享元素动画
SharedTransitionLayout {
NavHost(...) {
composable("list") {
Image(
modifier = Modifier.sharedElement(
state = rememberSharedContentState(key = "image"),
animatedVisibilityScope = this
)
)
}
}
}
四、最佳实践
- ✅ 使用 label 参数便于调试
- ✅ 选择合适的动画规格
- ✅ 使用 graphicsLayer 优化性能
- ✅ 共享元素使用唯一 key
总结
- Transition:协调多属性动画
- AnimatedContent:内容切换
- SharedElement:跨页面共享
- InfiniteTransition:循环动画