一.概述
记录一个添加购物车动画的demo。
第一步,得到商品图片的坐标。为了动画不相互影响,需要一个新的ImageView。需要一个接口把图片和坐标传到activity中处理
//设置回调动画起始坐标
Bitmap bitmap = ((BitmapDrawable) childHolder.home_goodsimg_iv.getDrawable()).getBitmap();
ImageView buyImg = new ImageView(mContext);
buyImg.setImageBitmap(bitmap);
int[] start_location = new int[2];
childHolder.home_goodsimg_iv.getLocationInWindow(start_location);
if (addCartAnim != null) {
addCartAnim.addCartAnim(buyImg, start_location);
}
第二步,实现方法,先创建动画布局,再把图片加进来。
private ViewGroup createAnimLayout() {
ViewGroup rootView = (ViewGroup)this.getWindow().getDecorView();//拿到根视图
LinearLayout animLayout = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
animLayout.setLayoutParams(params);
animLayout.setId(Integer.MAX_VALUE);
animLayout.setBackgroundResource(android.R.color.transparent);
rootView.addView(animLayout);
return animLayout;
}
private View addViewToAnimLayout(final ViewGroup vg, final View view,
int[] location) {
int x = location[0];
int y = location[1];
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.leftMargin = x;
lp.topMargin = y;
view.setLayoutParams(lp);
return view;
}
第三步,得到位移距离,设置动画。
@Override
public void setAnim(final View v, int[] location) {
anim_mask_layout = null;
anim_mask_layout = createAnimLayout();
anim_mask_layout.addView(v);
View view = addViewToAnimLayout(anim_mask_layout,v, location);
int[] end_location = new int[2];
home_shop_cart_iv.getLocationInWindow(end_location);
// 计算位移
/*Log.e("MainActivity", "start_locationX = "+location[0]+",start_locationY = "+location[1]+
",end_locationX = "+end_location[0]+",end_locationY = "+end_location[1]);*/
int endX = end_location[0] - location[0] - 40;// 动画位移的X坐标
int endY = end_location[1] - location[1] - 40;// 动画位移的y坐标
ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationY", 0,endY);
animator.setInterpolator(new AccelerateInterpolator());
ObjectAnimator animator2 = ObjectAnimator.ofFloat(view, "translationX", 0,endX);
animator2.setInterpolator(new LinearInterpolator());
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(animator).with(animator2);
animatorSet.playTogether(ObjectAnimator.ofFloat(view, "scaleX", 1.0f,0.1f),
ObjectAnimator.ofFloat(view, "scaleY", 1.0f,0.1f));
animatorSet.setDuration(500);
animatorSet.start();
animatorSet.addListener(new AnimatorListener() {
@Override
public void onAnimationStart(Animator arg0) {
v.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationRepeat(Animator arg0) {
}
@Override
public void onAnimationEnd(Animator arg0) {
v.setVisibility(View.GONE);
ObjectAnimator.ofFloat(home_shop_cart_iv, "scaleX", 1f,1.2f,1f).setDuration(200).start();
ObjectAnimator.ofFloat(home_shop_cart_iv, "scaleY", 1f,1.2f,1f).setDuration(200).start();
}
@Override
public void onAnimationCancel(Animator arg0) {
}
});
}