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

View动画进入onPause生命周期后自动停止,如何使其不中断?

解决View动画在组件Pause/Resume后停止的问题

你使用view.startAnimation(myAnimation)实现的动画,在组件进入onPause再回到onResume后停止,这是因为传统补间动画依赖系统的绘制调度,组件后台时系统会暂停这类动画。以下是几种可行的解决方案:

1. 记录动画进度,在Resume时恢复

在组件生命周期中记录动画的运行进度,恢复时从断点继续播放:

private Animation myAnimation;
private long animationElapsedTime = 0;
private boolean isAnimating = false;

@Override
protected void onPause() {
    super.onPause();
    if (myAnimation != null && myAnimation.hasStarted() && !myAnimation.hasEnded()) {
        animationElapsedTime = myAnimation.getCurrentTime();
        isAnimating = true;
        myAnimation.cancel();
    } else {
        isAnimating = false;
    }
}

@Override
protected void onResume() {
    super.onResume();
    if (isAnimating) {
        myAnimation.reset();
        // 从上次中断的时间点继续
        myAnimation.setStartTime(SystemClock.uptimeMillis() - animationElapsedTime);
        view.startAnimation(myAnimation);
    }
}

如果是循环动画,还需要额外记录已完成的循环次数,重新计算剩余循环参数。

2. 改用属性动画替代补间动画

属性动画(Property Animation)直接修改View的属性,默认不受组件Pause/Resume的影响,不会自动停止:

// 示例:平移动画
ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationX", 0f, 100f);
animator.setDuration(1000);
animator.setRepeatCount(ValueAnimator.INFINITE); // 无限循环
animator.start();

如果需要更精细的控制,可以通过AnimatorListener监听动画状态,或者设置animator.setAutoCancel(false)避免意外取消。

3. 自定义View内部驱动动画

通过自定义View结合postInvalidateOnAnimation实现自主驱动的动画,不受组件生命周期直接干扰:

public class AnimatedView extends View {
    private float animationProgress = 0f;
    private final ValueAnimator animator;

    public AnimatedView(Context context) {
        super(context);
        animator = ValueAnimator.ofFloat(0f, 1f);
        animator.setDuration(1000);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.addUpdateListener(animation -> {
            animationProgress = (float) animation.getAnimatedValue();
            postInvalidateOnAnimation(); // 触发下一次绘制
        });
        animator.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 根据进度绘制动画效果,比如平移
        float translateX = animationProgress * getWidth() / 2;
        canvas.save();
        canvas.translate(translateX, 0);
        // 绘制你的View内容
        canvas.restore();
    }
}

这种方式的动画由View自身维护,只要View未被销毁,就能持续运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 23:03:19