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

如何在Jetpack Compose中实现LottieAnimationView.setFrame(int frame)等效效果?

在Jetpack Compose中实现Lottie指定帧加载的等效方案

在Jetpack Compose中,你可以通过LottieAnimation组件配合LottieAnimator实现原生setFrame()的等效功能,核心是利用rememberLottieAnimator()提供的动画控制方法。

实现步骤

  1. 确认依赖配置
    确保项目中引入了Lottie Compose的最新稳定版依赖:

    implementation "com.airbnb.android:lottie-compose:6.4.0"
    
  2. 核心代码实现
    通过LocalAccessibilityManager判断系统辅助功能的动画禁用状态,结合动画控制器跳转到指定帧:

    @Composable
    fun ControlledLottieAnimation() {
        // 加载目标Lottie动画资源
        val composition by rememberLottieComposition(
            LottieCompositionSpec.RawRes(R.raw.your_lottie_asset)
        )
        // 获取Compose版Lottie动画控制器
        val animator = rememberLottieAnimator()
        // 获取系统辅助功能的动画禁用状态
        val accessibilityManager = LocalAccessibilityManager.current
        val shouldDisableAnimations = accessibilityManager?.disableAnimations ?: false
    
        LaunchedEffect(shouldDisableAnimations, composition) {
            if (shouldDisableAnimations && composition != null) {
                // 同步跳转到指定帧(无过渡动画,对应原生setFrame())
                animator.setFrame(frame = 50)
                // 禁止动画循环,保持静态帧状态
                animator.repeatCount = 0
            } else {
                // 正常播放动画
                animator.play()
            }
        }
    
        LottieAnimation(
            composition = composition,
            animator = animator,
            modifier = Modifier.size(200.dp)
        )
    }
    

关键方法说明

  • animator.setFrame(frame: Int):完全对应原生setFrame(),直接跳转到指定帧且无过渡动画,适合需要静态展示目标帧的场景。
  • animator.animateToFrame(frame: Int):带动画过渡跳转到指定帧,若需要平滑切换可使用此方法。
  • LocalAccessibilityManager:用于监听系统辅助功能中"关闭动画"的设置,自动触发帧切换逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:25:07