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

Android Xamarin:检测Lottie动画结束并实现DialogFragment自动关闭

解决方案

这问题我刚好处理过,给你一步步来实现需求:

核心思路

我们需要给Lottie动画添加动画结束监听,在动画播放完成后触发DialogFragment的关闭操作,同时要注意做好内存泄漏防护。

步骤1:在DialogFragment中设置监听并启动动画

在你的DialogFragment的onViewCreated方法中,拿到animView之后,添加如下代码:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val animView = view.findViewById<LottieAnimationView>(R.id.animViewTest1)
    
    // 创建动画监听对象
    val animEndListener = object : Animator.AnimatorListener {
        override fun onAnimationStart(animation: Animator?) {
            // 动画开始时的操作(可选,比如做一些状态标记)
        }

        override fun onAnimationEnd(animation: Animator?) {
            // 动画结束后直接关闭DialogFragment
            dismiss()
            // 及时移除监听,避免内存泄漏
            animView.removeAnimatorListener(this)
        }

        override fun onAnimationCancel(animation: Animator?) {
            // 动画被取消时也要移除监听
            animView.removeAnimatorListener(this)
        }

        override fun onAnimationRepeat(animation: Animator?) {
            // 因为你设置了loop=false,这个方法不会被触发,留空即可
        }
    }

    animView.addAnimatorListener(animEndListener)
    // 手动启动动画(布局里设置了autoPlay=false)
    animView.playAnimation()
}

步骤2:额外的内存泄漏防护(推荐)

为了更稳妥,你可以在DialogFragment销毁视图时,主动移除所有动画监听,避免因生命周期异常导致的内存泄漏:

// 先在DialogFragment里声明animView的成员变量
private var animView: LottieAnimationView? = null

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    animView = view.findViewById(R.id.animViewTest1)
    // 上面的监听和播放代码不变
}

override fun onDestroyView() {
    animView?.removeAllAnimatorListeners()
    animView = null // 置空成员变量,切断引用
    super.onDestroyView()
}

关键点说明

  • 因为你在布局里设置了app:lottie_autoPlay="false",所以必须手动调用playAnimation()来触发播放
  • 在onAnimationEnd中调用dismiss()就能直接关闭当前DialogFragment
  • 一定要在动画结束/取消时移除监听,避免持有DialogFragment的引用造成内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:08:04