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
相关产品推荐
相关产品推荐

