Android开发:Lottie动画无法运行且回调监听器未触发,求定位错误
问题分析与解决方案
核心错误点
- 自动播放配置冲突:XML中设置了
app:lottie_autoPlay="true",但View初始状态为gone,动画会在View不可见时自动执行完毕。后续手动调用playAnimation()时,动画已处于结束状态,无法触发回调。 - 监听器添加时机错误:若监听器是在
playAnimation()调用之后才添加,会导致监听器无法捕获已启动的动画事件。 - 未重置动画状态:如果动画之前已播放过,直接调用
playAnimation()可能不会重新触发完整的动画周期,自然不会触发回调。
修正方案
1. 移除自动播放配置
修改XML,关闭自动播放,避免View不可见时提前执行动画:
<com.airbnb.lottie.LottieAnimationView android:layout_width="@dimen/margin_15" android:layout_height="@dimen/margin_15" android:id="@+id/lav_LikeAnim" app:lottie_autoPlay="false" <!-- 改为false --> app:lottie_fileName="handshake_lottie.json" app:lottie_loop="false" android:visibility="gone" android:scaleX="2" android:scaleY="2" android:layout_gravity="center" />
2. 提前添加监听器
在页面初始化阶段(如onCreate/onViewCreated)就添加动画监听器,不要等到点赞事件触发时才添加:
// 示例:在Fragment的onViewCreated中初始化监听器 @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); likeLottieAnim = view.findViewById(R.id.lav_LikeAnim); // 提前添加监听器 likeLottieAnim.addAnimatorListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { iv_like.setVisibility(View.GONE); tv_likes_count.setVisibility(View.GONE); } @Override public void onAnimationEnd(Animator animation) { try { iv_like.setVisibility(View.VISIBLE); tv_likes_count.setVisibility(View.VISIBLE); likeLottieAnim.setVisibility(View.GONE); } catch (Exception exception) { exception.printStackTrace(); Logger.i(TAG,"Lottie_animation_exception :"+exception); } iv_like.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_liked)); } @Override public void onAnimationCancel(Animator animation) { Logger.i(TAG,"onAnimationCancel :"); } @Override public void onAnimationRepeat(Animator animation) { Logger.i(TAG,"onAnimationRepeat :"); } }); }
3. 播放前重置动画状态
调用playAnimation()前,先重置动画到初始状态,确保动画完整播放并触发回调:
try { // 重置动画至初始状态 likeLottieAnim.cancelAnimation(); likeLottieAnim.setProgress(0f); // 先设置View可见,再播放动画 likeLottieAnim.setVisibility(View.VISIBLE); likeLottieAnim.playAnimation(); iv_like.setVisibility(View.GONE); tv_likes_count.setVisibility(View.GONE); } catch (Exception exception) { exception.printStackTrace(); Logger.i(TAG,"Lottie_animation_exception :"+exception); }
内容的提问来源于stack exchange,提问作者Anuj Vaish
相关产品推荐
相关产品推荐

