添加购物车的动画效果相信很多开发者都用到过,近期听到过很多这样的需求,故此写了demo,直接上效果图:
- 这里的界面很简单,代码就不贴了,简单贴一下点击事件下的代码片段。
- parabola监听(抛物线)
- <span style="font-size:14px;">ValueAnim.startValue(iv_dot, screenHeight, 0, 1);</span>
- Free_Falling_body监听(自由落体,可设置X和Y方向)
- <span style="font-size:14px;">iv_dot.setX(tv_fallingBody.getX());
- iv_dot.setY(tv_fallingBody.getY());
- ValueAnim.startValue(iv_dot, "y", 0, screenHeight - tv_fallingBody.getHeight() - tv_fallingBody.getMeasuredHeight() - iv_dot.getMeasuredHeight() - iv_dot.getHeight());</span>
iv_dot:是要移动的view;screenHeight:是当前屏幕的高度;ValueAnim:是动画移动工具类。
下面贴ValueAnim类:
- <span style="font-size:14px;">public class ValueAnim {
- /**
- * 设置view的平移动画,可设置X或Y方向的平移
- *
- * @param view 要平移的view
- */
- public static void startValue(final View view, final String orientation, float from, float to) {
- ValueAnimator anim = ValueAnimator.ofFloat(from, to);
- anim.setTarget(view);
- anim.setDuration(2000);
- anim.setInterpolator(new AccelerateInterpolator());
- anim.start();
- anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
- @Override
- public void onAnimationUpdate(ValueAnimator animation) {
- if (orientation.equals("y")) {
- view.setTranslationY((Float) animation.getAnimatedValue());
- } else {
- view.setTranslationX((Float) animation.getAnimatedValue());
- }
- }
- });
- }
- /**
- * 抛物线
- *
- * @param view 要平移的view
- * @param screenHeight 当前屏幕高度
- * @param from
- * @param to
- */
- public static void startValue(final View view, final int screenHeight, float from, float to) {
- ValueAnimator anim = ValueAnimator.ofFloat(from, to);
- anim.setTarget(view);
- anim.setDuration(2000);
- anim.setInterpolator(new AccelerateInterpolator());
- anim.start();
- anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
- @Override
- public void onAnimationUpdate(ValueAnimator animation) {
- float value = (Float) animation.getAnimatedValue();
- view.setTranslationX(-130 * value * 3);//抛物线的x计算公式
- view.setTranslationY(0.5f * screenHeight * value * 3 * value * 3);
- }
- });
- }
- }</span>