網購App購物車點擊動畫實現
在做網購APP時,很多的app在點擊購物車時都有一個圖片動畫效果,比較形象,我目前做的項目也涉及到了,把我使用的方法做個筆記:
先看一個簡單的截圖:我們在點擊列表中帶+號的購物車時,會有一個圖片多點擊的購物車位置跑到右上角的購物車中,同時右上角的購物車數量增加1,實現原理很簡單,就是我們常用的位移動畫:
首先要個動畫層ViewGroup anim_mask_layout;動畫圖片就在這個動畫層上面移動:
創建動畫層代碼:
public ViewGroup createAnimLayout() {
ViewGroup rootView = (ViewGroup)this.getActivity().getWindow().getDecorView();
LinearLayout animLayout = new LinearLayout(getActivity());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
animLayout.setLayoutParams(lp);
animLayout.setId(Integer.MAX_VALUE);
animLayout.setBackgroundResource(android.R.color.transparent);
rootView.addView(animLayout);
return animLayout;
}
添加動畫視圖到動畫層:
public 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;
}
最后就是動畫實現:其中的第一個參數就是在你調用這個方法時傳入的動畫圖片,第二個參數是你傳入圖片所在的Location:
public void setTranslateAnim(final View v, int[] start_location) {
if(anim_mask_layout==null)
anim_mask_layout = createAnimLayout();
anim_mask_layout.addView(v);//把動畫視圖添加到動畫層
final View view = addViewToAnimLayout(anim_mask_layout, v,
start_location);
int[] end_location = new int[2];// 這是用來存儲動畫結束位置的X、Y坐標
shopCart.getLocationInWindow(end_location);// shopCart是那個購物車
// 計算位移
int endX = 0 ;// 動畫位移的X坐標
int endY = end_location[1] - start_location[1];// 動畫位移的y坐標
TranslateAnimation translateAnimationX = new TranslateAnimation(0,
endX, 0, 0);
translateAnimationX.setInterpolator(new LinearInterpolator());
translateAnimationX.setRepeatCount(0);// 動畫重復執行的次數
translateAnimationX.setFillAfter(true);
TranslateAnimation translateAnimationY = new TranslateAnimation(0, 0,
0, endY);
translateAnimationY.setInterpolator(new AccelerateInterpolator());
translateAnimationY.setRepeatCount(0);// 動畫重復執行的次數
translateAnimationX.setFillAfter(true);
AnimationSet set = new AnimationSet(false);
set.setFillAfter(false);
set.addAnimation(translateAnimationY);
set.addAnimation(translateAnimationX);
set.setDuration(800);// 動畫的執行時間
view.startAnimation(set);
// 動畫監聽事件
set.setAnimationListener(new AnimationListener() {
// 動畫的開始
@Override
public void onAnimationStart(Animation animation) {
v.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
// 動畫的結束
@Override
public void onAnimationEnd(Animation animation) {
v.setVisibility(View.GONE);
anim_mask_layout.removeView(view);
// buyNum++;//讓購買數量加1
}
});
}