// 获取自定义动画实例CustomRotateAnim rotateAnim = CustomRotateAnim.getCustomRotateAnim();// 一次动画执行0.2秒rotateAnim.setDuration(200);// 设置为循环播放rotateAnim.setRepeatCount(4);// 设置为匀速rotateAnim.setInterpolator(new LinearInterpolator());// 开始播放动画redlayout.startAnimation(rotateAnim);//动画状态监听rotateAnim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) {//开始 } @Override public void onAnimationEnd(Animation animation) {//结束 } @Override public void onAnimationRepeat(Animation animation) { }});
自定义类:
public class CustomRotateAnim extends Animation { /** 控件宽 */ private int mWidth; /** 控件高 */ private int mHeight; /** 实例 */ private static CustomRotateAnim rotateAnim; /** * 获取动画实例 * @return 实例 */ public static CustomRotateAnim getCustomRotateAnim() { if (null == rotateAnim) { rotateAnim = new CustomRotateAnim(); } return rotateAnim; } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { this.mWidth = width; this.mHeight = height; super.initialize(width, height, parentWidth, parentHeight); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { // 左右摇摆PI*2)*N控制摇摆幅度(N越小幅度越小),后面两个参数控制旋转中心点的位置 t.getMatrix().setRotate((float)(Math.sin(interpolatedTime*Math.PI*2)*5), mWidth/2, mHeight/2); super.applyTransformation(interpolatedTime, t); }}