Jetpack Compose - 在状态变化时播放复杂的动画

Fri*_*ice 6 kotlin android-jetpack-compose jetpack-compose-animation

如何使用协程在切换到特定状态时播放复杂的动画?

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

    val transition = updateTransition(targetState = state, label = "label")
    <on transitioning to CaptureState> { // need actual condition check code here
        scope.launch {
            animate(0f, 1f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
            animate(1f, 0f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Fri*_*ice 3

LaunchedEffect答案是:

@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)
    )

    LaunchedEffect(state) {
        if (state == CaptureState) {
            animate(0f, 1f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
            animate(1f, 0f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您不需要 `scope.launch`,`LaunchedEffect` 已经在协程作用域上运行。 (3认同)