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

Compose滑动动画咨询:按钮触发动画与日历月份切换滑动方案

Jetpack Compose 滑动动画实现问题

我刚开始学习Jetpack Compose,需要实现两个动画需求:

  • 点击按钮触发的单次滑动动画
  • 为日程规划器的自定义日历实现月份切换时的左右滑动效果

我尝试通过协程配合AnimatedVisibility的退出与进入过渡+延迟的方式实现,但这种方法存在问题且容易出现bug。为简化代码逻辑,我制作了一个具有相同动画实现逻辑的小型Demo:

val animDuration = 100
var visible by remember { mutableStateOf(true) }

//Required for variable transitions for each button
val enterTransition = remember { mutableStateOf(EnterTransition.None) }
val exitTransition = remember { mutableStateOf(ExitTransition.None) }

val coroutineScope = rememberCoroutineScope()

Row(
    modifier = Modifier.fillMaxWidth(),
    horizontalArrangement = Arrangement.SpaceBetween,
    verticalAlignment = Alignment.CenterVertically
) {

    ButtonLeft {
        // Here I change the initialOffsetX of the enter transition
        // and the targetOffsetX of the exit transition
        // so that the RedBox goes to the right and appears on the left.

        enterTransition.value = slideInHorizontally(
            initialOffsetX = { -2*it },
            animationSpec = tween(animDuration, easing = LinearEasing)
        )
        exitTransition.value = slideOutHorizontally(
            targetOffsetX = { 2*it },
            animationSpec = tween(animDuration, easing = LinearEasing)
        )

        // Here I turn off RedBox visibility,
        // wait for the animation end with a delay,
        // and then turn on visibility
        coroutineScope.launch(context = Dispatchers.Main) {
            visible = false
            delay(200)
            visible = true
        }
    }

    AnimatedVisibility(
        visible = visible,
        enter = enterTransition.value + fadeIn(tween(animDuration)),
        exit = exitTransition.value + fadeOut(tween(animDuration))
    ) {
        RedBox()
    }

    ButtonRight {

        // Here RedBox goes to the left and appears on the right.

        enterTransition.value = slideInHorizontally(
            initialOffsetX = { 2*it },
            animationSpec = tween(animDuration, easing = LinearEasing)
        )
        exitTransition.value = slideOutHorizontally(
            targetOffsetX = { -2*it },
            animationSpec = tween(animDuration, easing = LinearEasing)
        )

        coroutineScope.launch(context = Dispatchers.Main) {
            visible = false
            delay(200)
            visible = true
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 13:57:28