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

Android中AnimationListener的onAnimationRepeat方法未触发问题求助

解决AnimationListener中onAnimationRepeat()不触发的问题

嘿,我来帮你搞定这个onAnimationRepeat()不触发的问题!先拆解一下核心原因,再给你两种可行的解决方案。

问题根源

你用的是Android传统的View Animation(视图动画),这个框架里有个容易踩的坑:当动画设置了repeatMode="reverse"时,onAnimationRepeat()方法不会被触发。这个回调仅在动画以restart模式重复(也就是重新从起始状态正向播放)时才会被调用,而反向播放的过程,系统并不认为是“重复”,所以不会触发这个回调。

你的XML里刚好设置了android:repeatMode="reverse",这就是为什么onAnimationRepeat()始终没反应的核心原因。

解决方案

方案一:修改repeatMode为restart(简单快速)

如果你的业务场景允许动画重复时重新从开头播放,那直接把XML里的repeatMode改成restart就行,这样每次重复都会触发onAnimationRepeat()。

修改后的动画XML:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <scale
 android:interpolator="@android:anim/accelerate_decelerate_interpolator"
 android:duration="1000"
 android:fillAfter="true"
 android:fromXScale="0.0"
 android:fromYScale="0.0"
 android:toXScale="1.0"
 android:toYScale="1.0"
 android:repeatMode="restart" <!-- 这里修改 -->
 android:repeatCount="5"
 android:pivotX="50%"
 android:pivotY="50%" />
</set>

方案二:改用属性动画(推荐,更灵活)

如果你需要保留反向播放的效果,同时还要监听重复事件,我强烈建议你改用属性动画(Property Animation)。属性动画是Android 3.0之后推出的更强大的动画框架,它的AnimatorListener里的onAnimationRepeat()不管是restart还是reverse模式都会正常触发,而且功能更丰富,也更符合现代Android开发的最佳实践。

替换原来的startAnimation方法的示例代码:

public void startAnimation(View view){
    // 小优化:把findViewById移到onCreate里初始化会更高效,这里先按你的逻辑保留
    textView = findViewById(R.id.tvMessage);
    
    // 创建缩放X和Y的属性动画
    ObjectAnimator scaleX = ObjectAnimator.ofFloat(textView, "scaleX", 0f, 1f);
    ObjectAnimator scaleY = ObjectAnimator.ofFloat(textView, "scaleY", 0f, 1f);
    
    // 组合两个动画,同步播放
    AnimatorSet animSet = new AnimatorSet();
    animSet.playTogether(scaleX, scaleY);
    animSet.setDuration(1000);
    animSet.setInterpolator(new AccelerateDecelerateInterpolator());
    animSet.setRepeatCount(5);
    animSet.setRepeatMode(ValueAnimator.REVERSE); // 保持反向重复
    
    animSet.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
            Log.d("MY_TAG", "Animation Started!!!");
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            Log.d("MY_TAG", "Animation End!!!");
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            // 可选:处理动画取消的逻辑
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
            Log.d("MY_TAG", "Repeating..."); // 现在会正常触发了!
        }
    });
    
    animSet.start();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:14:18