You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose如何简便实现Composable随变量切换的显隐动画

简便实现方案

针对你的动态内容切换场景,有两种几乎不用改动原有业务逻辑的实现方案,仅需额外嵌套1层系统提供的动画组件即可:

场景1:同一时间仅展示1种类型的内容

如果contentType是单值变量,直接用AnimatedContent绑定该变量即可,默认自带淡入淡出+缩放过渡效果:

// 仅需在原有逻辑外层套AnimatedContent,targetState绑定contentType
AnimatedContent(targetState = contentType, label = "contentTypeSwitchAnim") { currentType ->
    when (currentType) {
        ContentType.Type1 -> ComposableForType1()
        ContentType.Type2 -> ComposableForType2()
        ContentType.Type3 -> ComposableForType3()
        ContentType.Type4 -> ComposableForType4()
    }
}
// 原有修改contentType的逻辑完全不需要改动

需要自定义动画效果时,仅需补充transitionSpec参数即可,例如配置滑入滑出效果:

AnimatedContent(
    targetState = contentType,
    transitionSpec = {
        slideInHorizontally { it } + fadeIn() togetherWith slideOutHorizontally { -it } + fadeOut()
    },
    label = "contentTypeSwitchAnim"
) { /* 内部when逻辑和上面一致 */ }

场景2:同一时间可展示多个类型的内容

如果contentType是集合类型(对应你代码里的forEach遍历逻辑),遍历所有枚举值后给每个项套AnimatedVisibility,判断当前类型是否在集合中即可:

ContentType.values().forEach { type ->
    AnimatedVisibility(
        visible = type in contentType,
        label = "itemAnim_${type.name}"
    ) {
        when (type) {
            ContentType.Type1 -> ComposableForType1()
            ContentType.Type2 -> ComposableForType2()
            ContentType.Type3 -> ComposableForType3()
            ContentType.Type4 -> ComposableForType4()
        }
    }
}
// 原有修改contentType集合的逻辑完全不需要改动

如需自定义单组件的显隐效果,补充enter和exit参数即可。

内容的提问来源于stack exchange,提问作者Tim Yumalin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:15:03