如何停止animation(取消()不起作用)
我需要停止正在运行的翻译animation。 Animation
的.cancel()
方法没有效果; 无论如何,animation直到结束。
你如何取消正在运行的animation?
调用clearAnimation()
,无论哪个View
调用startAnimation()
。
在Android 4.4.4上,似乎唯一能阻止View上的alpha衰落animation的方式是调用View.animate().cancel()
(即在View的ViewPropertyAnimator
上调用.cancel()
。
以下是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; }
这是我停止的animation:
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);
如果您正在使用animation侦听器,请设置v.setAnimationListener(null)
。 对所有选项使用下面的代码。
v.getAnimation().cancel(); v.clearAnimation(); animation.setAnimationListener(null);
你必须使用.clearAnimation(); UI线程中的方法:
runOnUiThread(new Runnable() { @Override public void run() { v.clearAnimation(); } });
你可以尝试做的是在停止animation之前从animation中获得变换matrix,然后检查matrix内容以获取所需的位置值。
这里是你应该看看的API
public boolean getTransformation (long currentTime, Transformation outTransformation)
public Matrix getMatrix ()
public void getValues (float[] values)
所以例如(一些伪代码,我没有testing过):
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];
使用setAnimation(null)方法停止一个animation,它在View.java中作为公共方法公开 ,它是所有小部件的基类,用于创build交互式UI组件(button,文本字段等)。 /** * Sets the next animation to play for this view. * If you want the animation to play immediately, use * {@link #startAnimation(android.view.animation.Animation)} instead. * This method provides allows fine-grained * control over the start time and invalidation, but you * must make sure that 1) the animation has a start time set, and * 2) the view's parent (which controls animations on its children) * will be invalidated when the animation is supposed to * start. * * @param animation The next animation, or null. */ public void setAnimation(Animation animation)