Jetpack Compose如何实现两个Icon的淡入淡出切换动画
Jetpack Compose 图标交叉淡入淡出切换实现方案
你可以使用Compose官方动画库提供的AnimatedContent组件实现需求,该组件天然支持状态变化时的内容切换动画,无需自定义复杂的动画逻辑。
实现代码
将你原有if-else的图标显示逻辑包裹在AnimatedContent中即可,完整示例如下:
// 若项目未引入Compose动画依赖,需先在build.gradle(Module级)的dependencies中添加,版本与项目Compose版本一致 // implementation "androidx.compose.animation:animation:你的Compose版本号" // 若使用的Compose版本较低,AnimatedContent属于实验性API,添加该注解即可 @OptIn(ExperimentalAnimationApi::class) @Composable fun ToggleCheckIcon(isChecked: Boolean) { AnimatedContent( targetState = isChecked, transitionSpec = { // 配置淡入和淡出动画同时执行,实现交叉切换效果 fadeIn(animationSpec = tween(durationMillis = 300)) togetherWith fadeOut(animationSpec = tween(durationMillis = 300)) }, label = "CheckCloseIconToggleAnimation" ) { currentCheckedState -> if (currentCheckedState) { Icon( imageVector = Icons.Default.Check, contentDescription = "", tint = Color.Black ) } else { Icon( imageVector = Icons.Default.Close, contentDescription = "", tint = Color.Gray ) } } }
参数调整说明
- 可以修改
tween中的durationMillis参数调整动画持续时长,单位为毫秒 - 如需添加其他动画效果,可在
transitionSpec中组合scaleIn/scaleOut等其他内置动画,例如添加缩放效果的代码如下:
transitionSpec = { (fadeIn(tween(300)) + scaleIn(initialScale = 0.8f, animationSpec = tween(300))) togetherWith (fadeOut(tween(300)) + scaleOut(targetScale = 1.2f, animationSpec = tween(300))) }
内容的提问来源于stack exchange,提问作者barryalan2633
相关产品推荐
相关产品推荐

