android动画工具类
import android.content.Context; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.CycleInterpolator; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; /** * 动画工具类 * Created by Administrator on 2015/10/20 0020. */ public class AnimUtils { /** * 抖动动画,左右抖动 * @param context 上下文 * @param v 要执行动画的view */ public static void shake(Context context,View v){ Animation shake = new TranslateAnimation(0, 10, 0, 0);//移动方向 shake.setDuration(1000);//执行总时间 shake.setInterpolator(new CycleInterpolator(7));//循环次数 v.startAnimation(shake); } /** * 缩放动画,按下时缩放,抬起时恢复 * @param v 要执行动画的view * @param event 触摸事件 * @param listener 点击事件 * @return 触摸结果 */ public static boolean setClickAnim(View v,MotionEvent event,OnClickListener listener){ float start = 1.0f; float end = 0.95f; Animation scaleAnimation = new ScaleAnimation(start, end, start, end, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); Animation endAnimation = new ScaleAnimation(end, start, end, start, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); scaleAnimation.setDuration(200); scaleAnimation.setFillAfter(true); endAnimation.setDuration(200); endAnimation.setFillAfter(true); switch (event.getAction()) { // 按下时调用 case MotionEvent.ACTION_DOWN: v.startAnimation(scaleAnimation); v.invalidate(); break; // 抬起时调用 case MotionEvent.ACTION_UP: v.startAnimation(endAnimation); v.invalidate(); if(listener!=null){ listener.onClick(v); } break; // 滑动出去不会调用action_up,调用action_cancel case MotionEvent.ACTION_CANCEL: v.startAnimation(endAnimation); v.invalidate(); break; } // 不返回true,Action_up就响应不了 return true; } }
调用方法
1、抖动动画
AnimUtils.shake(context, view);
2、缩放动画(先implements OnClickListener,OnTouchListener再重写onTouch方法)
public boolean onTouch(View v, MotionEvent ev) { return AnimUtils.setClickAnim(v, ev, this);
}