如何从停止时的值开始Android动画?

问题描述 投票:0回答:2

我有一个图像视图,我在其上应用了旋转动画。动画效果很好。着陆时,我尝试使用cancel()停止旋转动画,使用reset()重置动画并使用clearAnimation()清除视图上的动画。但动画又回到了原来的位置。如何使用触地事件发生时的值停止动画并从停止的位置重新启动?

我的动画在xml中定义如下

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="360"
    android:toDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:fillAfter="true"
    android:fillEnabled="true"
    android:duration="200000"
    android:repeatMode="restart"
    android:repeatCount="infinite"
    android:interpolator="@android:anim/linear_interpolator"/>

我正在尝试使用以下代码停止动画

private void stopAnimation(){
        mRotateAntiClockwiseAnimation.cancel();
    mRotateAntiClockwiseAnimation.reset();
    imageView.clearAnimation();
    mRotateAntiClockwiseAnimator.end();
    mRotateAntiClockwiseAnimator.cancel();
    stopAnimationForImageButton();
    }

我使用以下代码在我的视图上设置动画

mRotateAntiClockwiseAnimation = AnimationUtils.loadAnimation(context, R.anim.rotate_anticlockwise);
        mRotateAntiClockwiseAnimation.setFillEnabled(true);
        mRotateAntiClockwiseAnimation.setFillAfter(true);
        imageView.setAnimation(mRotateAntiClockwiseAnimation);
        mRotateAntiClockwiseAnimation.startNow();
        imageView.invalidate();

正如你所见,即使使用cancel()或reset()也无助于将动画停止在触地的位置。任何指示都会有所帮助

android animation
2个回答
4
投票

我认为我通过启动动画师然后设置 currentPlayTime() 来使其工作。文档清楚地告诉(我刚刚偶然发现),如果动画尚未开始,使用此方法设置的 currentPlayTime 将不会向前推进!

将动画的位置设置到指定的时间点。该时间应介于 0 和动画的总持续时间(包括任何重复)之间。如果动画还没有开始,那么设置到这个时间后就不再前进;它只会将时间设置为该值,并根据该时间执行任何适当的操作。如果动画已经在运行,则 setCurrentPlayTime() 会将当前播放时间设置为此值并从该点继续播放。 http://developer.android.com/reference/android/animation/ValueAnimator.html#setCurrentPlayTime(长)

    private void stopAnimation(){
        mCurrentPlayTime = mRotateAntiClockwiseAnimator.getCurrentPlayTime();
        mRotateAntiClockwiseAnimator.cancel();
    }

    private void startAnimation() {
            mRotateAntiClockwiseAnimator.start();
            mRotateAntiClockwiseAnimator.setCurrentPlayTime(mCurrentPlayTime);
    }

0
投票

API 级别 19 中添加了暂停功能。在这里您可以阅读如何实现它。此方法使用 ObjectAnimator ,它并不比您通常使用的 Animation 类复杂多少。然而,还有另一个有用的替代技巧

© www.soinside.com 2019 - 2024. All rights reserved.