项目中运用到移动View位置,向使得移动过程更加鲜活一些,使用到动画并做记录小结:
创建并绑定动画到指定View,动画播放结束后如果需要停留在移动后的位置,那么设置View的位置;
/** * 动画移动view并摆放至相应的位置 * * @param view 控件 * @param xFromDeltaDistance x起始位置的偏移量 * @param xToDeltaDistance x终止位置的偏移量 * @param yFromDeltaDistance y起始位置的偏移量 * @param yToDeltaDistance y终止位置的偏移量 * @param duration 动画的播放时间 * @param delay 延迟播放时间 * @param isBack 是否需要返回到开始位置 */ public static void moveViewWithAnimation(final View view, final float xFromDeltaDistance, final float xToDeltaDistance, final float yFromDeltaDistance, final float yToDeltaDistance, int duration, int delay, final boolean isBack) { //创建位移动画 TranslateAnimation ani = new TranslateAnimation(xFromDeltaDistance, xToDeltaDistance, yFromDeltaDistance, yToDeltaDistance); ani.setInterpolator(new OvershootInterpolator());//设置加速器 ani.setDuration(duration);//设置动画时间 ani.setStartOffset(delay);//设置动画延迟时间 //监听动画播放状态 ani.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { int deltaX = (int) (xToDeltaDistance - xFromDeltaDistance); int deltaY = (int) (yToDeltaDistance - yFromDeltaDistance); int layoutX = view.getLeft(); int layoutY = view.getTop(); int tempWidth = view.getWidth(); int tempHeight = view.getHeight(); view.clearAnimation(); if (isBack == false) { layoutX += deltaX; layoutY += deltaY; view.layout(layoutX, layoutY, layoutX + tempWidth, layoutY + tempHeight); } else { view.layout(layoutX, layoutY, layoutX + tempWidth, layoutY + tempHeight); } } }); view.startAnimation(ani); }
延伸:
android的动画基本知识
android中提供了4中动画:
AlphaAnimation 透明度动画效果
ScaleAnimation 缩放动画效果
TranslateAnimation 位移动画效果
RotateAnimation 旋转动画效果
文中加速器的使用
效果 | 代码中方法 | xml中属性 |
---|---|---|
越来越快 | AccelerateInterpolator() | @android:anim/accelerate_interpolator |
越来越慢 | DecelerateInterpolator() | @android:anim/decelerate_interpolator |
先快后慢 | AccelerateDecelerateInterpolator() | @android:anim/accelerate_decelerate_interpolator |
先后退一小步然后向前加速 | AnticipateInterpolator() | @android:anim/anticipate_interpolator |
快速到达终点超出一小步然后回到终点 | OvershootInterpolator() | @android:anim/overshoot_interpolator |
到达终点超出一小步然后回到终点 | AnticipateOvershootInterpolator() | @android:anim/anticipate_overshoot_interpolator |
弹球效果,弹几下回到终点 | BounceInterpolator() | @android:anim/bounce_interpolator |
均匀速度 | LinearInterpolator() | @android:anim/linear_interpolator |