我需要停止一个运行翻译动画。Animation的.cancel()方法没有效果;不管怎样,动画会一直播放到最后。

如何取消正在运行的动画?


当前回答

在你调用startAnimation()的视图上调用clearAnimation()。

其他回答

在你调用startAnimation()的视图上调用clearAnimation()。

你可以尝试做的是在停止动画之前从动画中获取变换矩阵,并检查矩阵内容以获得你正在寻找的位置值。

下面是您应该研究的api

gettransform (long currentTime, transform outTransformation)

getMatrix ()

getValues (float[] values)

例如(一些伪代码。我还没有测试这个):

Transformation outTransformation = new Transformation();
myAnimation.getTransformation(currentTime, outTransformation);
Matrix transformationMatrix = outTransformation.getMatrix();
float[] matrixValues = new float[9];
transformationMatrix.getValues(matrixValues);
float transX = matrixValues[Matrix.MTRANS_X];
float transY = matrixValues[Matrix.MTRANS_Y];

因为没有其他答案提到它,你可以很容易地使用ValueAnimator的cancel()停止动画。

ValueAnimator在制作动画方面非常强大。下面是一个使用ValueAnimator创建翻译动画的示例代码:

ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, 5f);

int mDuration = 5000; //in millis
valueAnimator.setDuration(mDuration);

valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

   @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        // Update your view's x or y coordinate
    }
});

valueAnimator.start();

然后通过调用停止动画

valueAnimator.cancel()`

在Android 4.4.4,似乎唯一的方法我可以停止一个alpha淡出动画的视图是调用View.animate().cancel()(即,调用.cancel()在视图的ViewPropertyAnimator)。

以下是我在ICS之前和之后使用的兼容性代码:

public void stopAnimation(View v) {
    v.clearAnimation();
    if (canCancelAnimation()) {
        v.animate().cancel();
    }
}

…计算方法:

/**
 * Returns true if the API level supports canceling existing animations via the
 * ViewPropertyAnimator, and false if it does not
 * @return true if the API level supports canceling existing animations via the
 * ViewPropertyAnimator, and false if it does not
 */
public static boolean canCancelAnimation() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}

这是我正在停止的动画:

v.setAlpha(0f);
v.setVisibility(View.VISIBLE);
// Animate the content view to 100% opacity, and clear any animation listener set on the view.
v.animate()
    .alpha(1f)
    .setDuration(animationDuration)
    .setListener(null);

用这种方式:

// start animation
TranslateAnimation anim = new TranslateAnimation( 0, 100 , 0, 100);
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);

// end animation or cancel that
view.getAnimation().cancel();
view.clearAnimation();

取消()

取消动画。取消一个动画会调用该动画 监听器,如果设置,通知动画的结束。 如果手动取消动画,则必须调用reset() 在再次开始动画之前。


clearAnimation ()

取消此视图的任何动画。