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

Jetpack Compose 状态切换时播放复杂动画的实现方案

实现方案:Jetpack Compose 切换到特定状态时通过协程播放复杂动画

你要实现切换到CaptureState时触发快门闪烁动画,最简洁安全的实现方式如下:

核心修正逻辑

你不需要手动创建rememberCoroutineScope,直接使用Compose内置的LaunchedEffect即可,它天生绑定Composable生命周期,自带协程作用域,在监听的状态变化时自动执行代码,退出时自动取消任务,避免内存泄漏。
原来代码中<on transitioning to CaptureState>的位置,替换为LaunchedEffect监听状态变化的逻辑即可。

完整可运行代码示例

@Composable
fun SomeView(viewModel: SomeViewModel) {
    val state by viewModel.stateFlow.collectAsState()
    // 注意这里去掉了多余的rememberCoroutineScope声明
    
    val shutterAlpha by remember { mutableStateOf(0f) }
    Box(modifier = Modifier
        .fillMaxSize()
        .alpha(shutterAlpha)
        .background(Color.Black)
    )

    // 核心逻辑:监听state变化,进入CaptureState时触发动画
    LaunchedEffect(state) {
        if (state == CaptureState) {
            animate(0f, 1f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
            animate(1f, 0f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
        }
    }
}

如果你希望使用Transition API实现,也可以用以下写法

@Composable
fun SomeView(viewModel: SomeViewModel) {
    val state by viewModel.stateFlow.collectAsState()
    val shutterAlpha by remember { mutableStateOf(0f) }
    Box(modifier = Modifier
        .fillMaxSize()
        .alpha(shutterAlpha)
        .background(Color.Black)
    )

    val transition = updateTransition(targetState = state, label = "shutter_transition")
    // 监听切换到CaptureState的时机
    transition.onTransitionTo(CaptureState) {
        animate(0f, 1f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
        animate(1f, 0f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
    }
}

注意事项

  • 第一种方案更轻量,适合只需要触发单次顺序动画的场景
  • 第二种方案适合同时关联多个状态的复杂过渡动画场景
  • 注意导入androidx.compose.animation.core.animate、androidx.compose.runtime.LaunchedEffect等依赖
  • 如果用by代理mutableStateOf,需要提前导入androidx.compose.runtime.getValue和androidx.compose.runtime.setValue

内容的提问来源于stack exchange,提问作者Fried Rice

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:36:06