效果:
一、使用Animation(补间动画)
1.1代码实现
/** * 晃动动画 * * @param counts 0.5秒钟晃动多少下 * @return */ public static Animation shakeAnimation(int counts) { Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0); //设置一个循环加速器,使用传入的次数就会出现摆动的效果。 translateAnimation.setInterpolator(new CycleInterpolator(counts)); translateAnimation.setDuration(500); return translateAnimation; } /** * 0.1秒钟摇动3下 * @param counts * @param view */ public static void overshootAnimation(int counts, View view) { TranslateAnimation animation = new TranslateAnimation(0, -5, 0, 0); animation.setInterpolator(new OvershootInterpolator()); animation.setDuration(100); animation.setRepeatCount(3); animation.setRepeatMode(Animation.REVERSE); view.startAnimation(animation); }
1.2xml动画布局文件实现
shake_two.xml
<translate xmlns:android="http://schemas.android.com/apk/res/android" android:duration="500" android:fromXDelta="0" android:interpolator="@anim/cycle" android:toXDelta="10"/>
cycle.xml
<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android" android:cycles="3" > </cycleInterpolator>
使用
//xml动画布局文件实现 Animation animationTwo = AnimationUtils.loadAnimation(this, R.anim.shake_two); editText_shake.setAnimation(animationTwo); animationTwo.start();
二、使用属性动画ObjectAnimator
/** * 指定时间内进行左右晃动 * @param view * @param delta 左右偏移 * @param duration * @return */ public static ObjectAnimator shakeKeyframe(View view, int delta,int duration) { PropertyValuesHolder pvhTranslateX = PropertyValuesHolder.ofKeyframe(View.TRANSLATION_X, //Keyframe是一个时间/值对,用于定义在某个时刻动画的状态。 //比如Keyframe.ofFloat(.10f, -10)定义了当动画进行了50%的时候,x轴的偏移值应该是-10。 Keyframe.ofFloat(0f, 0), Keyframe.ofFloat(.1f, -delta), Keyframe.ofFloat(.2f, delta), Keyframe.ofFloat(.3f, -delta), Keyframe.ofFloat(.5f, delta), Keyframe.ofFloat(.7f, -delta), Keyframe.ofFloat(.9f, delta), Keyframe.ofFloat(1f, 0f) ); return ObjectAnimator.ofPropertyValuesHolder(view, pvhTranslateX). setDuration(duration); }
。。。
参考:
http://blog.csdn.net/howlaa/article/details/43152309
http://blog.csdn.net/zhangcanyan/article/details/54906935
http://www.apkbus.com/forum.php?mod=viewthread&tid=257854&highlight=%E5%8A%A8%E7%94%BB