步骤:
1)建立一个动画层
private ViewGroup createAnimLayout() {
ViewGroup rootView = (ViewGroup) this.getWindow().getDecorView();
LinearLayout animLayout = new LinearLayout(this);
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;
}
由此可知建立的动画层加入到了DecorView中。
2)利用TranslateAnimation分别设置X,Y的速度偏移位置等属性。通过设置translateAnimationX.setInterpolator();可以设置x,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);// 动画重复执行的次数
translateAnimationY.setFillAfter(true);//设置动画结束后保持当前的位置
源码:
MainActivity:
package com.dye.addshopcart;
import java.util.ArrayList;
import java.util.List;
import com.chen.mytest.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
/** * ListView鐨勫姞鍏ヨ喘鐗╄溅鍔ㄧ敾 * * @author OutTime * */
public class MainActivity extends Activity {
private ListView mListView;//商品listView
private Context mContext;
private ProductAdapter productAdapter;
private ImageView shopCart;//购物车
private ViewGroup anim_mask_layout;//动画层
private ImageView ball;// 小圆点
private int buyNum = 0;//购买数量
private BadgeView buyNumView;//购物车上的数量标签
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
initView();
}
private void initView() {
shopCart = (ImageView) findViewById(R.id.shopping_img_cart);
buyNumView = new BadgeView(mContext, shopCart);
buyNumView.setTextColor(Color.WHITE);
buyNumView.setBackgroundColor(Color.RED);
buyNumView.setTextSize(12);
mListView = (ListView) findViewById(R.id.product_list);
productAdapter = new ProductAdapter(getData());
mListView.setAdapter(productAdapter);
}
/** * * @return 测试数据 */
private List<String> getData() {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 20; i++) {
list.add("外卖" + i);
}
return list;
}
private class ProductAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<String> dataLsit;
public ProductAdapter(List<String> data) {
inflater = LayoutInflater.from(mContext);
dataLsit = data;
}
@Override
public int getCount() {
return dataLsit.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return dataLsit.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String name = dataLsit.get(position);
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.product_item, null);
holder = new ViewHolder();
holder.nameTxt = (TextView) convertView.findViewById(R.id.name);
holder.img = (ImageView) convertView.findViewById(R.id.im);
holder.buyBtn = (Button) convertView
.findViewById(R.id.product_buy_btn);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.nameTxt.setText(name);
holder.img.setImageResource(R.drawable.chi2);
//购买按钮的点击事件监听
holder.buyBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int[] startLocation = new int[2];// 一个整型数组,用来存储按钮的在屏幕的X、Y坐标
v.getLocationInWindow(startLocation);// 这是获取购买按钮的在屏幕的X、Y坐标(这也是动画开始的坐标)
ball = new ImageView(mContext);// buyImg是动画的图片,我的是一个小球(R.drawable.sign)
ball.setImageResource(R.drawable.sign);// 设置buyImg的图片
setAnim(ball, startLocation);// 开始执行动画
}
});
return convertView;
}
class ViewHolder {
TextView nameTxt;
Button buyBtn;
ImageView img;
}
}
/** * @Description: 创建动画层 * @param * @return void * @throws */
private ViewGroup createAnimLayout() {
ViewGroup rootView = (ViewGroup) this.getWindow().getDecorView();
LinearLayout animLayout = new LinearLayout(this);
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;
}
// private View addViewToAnimLayout(final ViewGroup parent, 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;
// }
private View addViewToAnimLayout( 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;
}
private void setAnim(final View v, int[] startLocation) {
anim_mask_layout = null;
anim_mask_layout = createAnimLayout();//设置动画层
anim_mask_layout.addView(v);//把动画小球添加到动画层
final View view = addViewToAnimLayout( v,
startLocation);//设置了小球的位置
int[] endLocation = new int[2];// 存储动画结束位置的X、Y坐标
shopCart.getLocationInWindow(endLocation);// shopCart是那个购物车
// 计算位移
int endX = 0 - startLocation[0] + 40;// 动画位移的X坐标
int endY = endLocation[1] - startLocation[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);// 动画重复执行的次数
translateAnimationY.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);
buyNum++;//让购买数量加1
buyNumView.setText(buyNum + "");//
buyNumView.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
buyNumView.show();
}
});
}
}
BadgeView:
package com.dye.addshopcart;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.TabWidget;
import android.widget.TextView;
/** * A simple text label view that can be applied as a "badge" to any given {@link android.view.View}. * This class is intended to be instantiated at runtime rather than included in XML layouts. * * @author Jeff Gilfelt */
public class BadgeView extends TextView {
public static final int POSITION_TOP_LEFT = 1;
public static final int POSITION_TOP_RIGHT = 2;
public static final int POSITION_BOTTOM_LEFT = 3;
public static final int POSITION_BOTTOM_RIGHT = 4;
public static final int POSITION_CENTER = 5;
private static final int DEFAULT_MARGIN_DIP = 5;
private static final int DEFAULT_LR_PADDING_DIP = 5;
private static final int DEFAULT_CORNER_RADIUS_DIP = 8;
private static final int DEFAULT_POSITION = POSITION_TOP_RIGHT;
private static final int DEFAULT_BADGE_COLOR = Color.parseColor("#CCFF0000"); //Color.RED;
private static final int DEFAULT_TEXT_COLOR = Color.WHITE;
private static Animation fadeIn;
private static Animation fadeOut;
private Context context;
private View target;
private int badgePosition;
private int badgeMarginH;
private int badgeMarginV;
private int badgeColor;
private boolean isShown;
private ShapeDrawable badgeBg;
private int targetTabIndex;
public BadgeView(Context context) {
this(context, (AttributeSet) null, android.R.attr.textViewStyle);
}
public BadgeView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.textViewStyle);
}
/** * Constructor - * * create a new BadgeView instance attached to a target {@link android.view.View}. * * @param context context for this view. * @param target the View to attach the badge to. */
public BadgeView(Context context, View target) {
this(context, null, android.R.attr.textViewStyle, target, 0);
}
/** * Constructor - * * create a new BadgeView instance attached to a target {@link android.widget.TabWidget} * tab at a given index. * * @param context context for this view. * @param target the TabWidget to attach the badge to. * @param index the position of the tab within the target. */
public BadgeView(Context context, TabWidget target, int index) {
this(context, null, android.R.attr.textViewStyle, target, index);
}
public BadgeView(Context context, AttributeSet attrs, int defStyle) {
this(context, attrs, defStyle, null, 0);
}
public BadgeView(Context context, AttributeSet attrs, int defStyle, View target, int tabIndex) {
super(context, attrs, defStyle);
init(context, target, tabIndex);
}
private void init(Context context, View target, int tabIndex) {
this.context = context;
this.target = target;
this.targetTabIndex = tabIndex;
// apply defaults
badgePosition = DEFAULT_POSITION;
badgeMarginH = dipToPixels(DEFAULT_MARGIN_DIP);
badgeMarginV = badgeMarginH;
badgeColor = DEFAULT_BADGE_COLOR;
setTypeface(Typeface.DEFAULT_BOLD);
int paddingPixels = dipToPixels(DEFAULT_LR_PADDING_DIP);
setPadding(paddingPixels, 0, paddingPixels, 0);
setTextColor(DEFAULT_TEXT_COLOR);
fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator());
fadeIn.setDuration(200);
fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(200);
isShown = false;
if (this.target != null) {
applyTo(this.target);
} else {
show();
}
}
private void applyTo(View target) {
LayoutParams lp = target.getLayoutParams();
ViewParent parent = target.getParent();
FrameLayout container = new FrameLayout(context);
if (target instanceof TabWidget) {
// set target to the relevant tab child container
target = ((TabWidget) target).getChildTabViewAt(targetTabIndex);
this.target = target;
((ViewGroup) target).addView(container,
new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
this.setVisibility(View.GONE);
container.addView(this);
} else {
// TODO verify that parent is indeed a ViewGroup
ViewGroup group = (ViewGroup) parent;
int index = group.indexOfChild(target);
group.removeView(target);
group.addView(container, index, lp);
container.addView(target);
this.setVisibility(View.GONE);
container.addView(this);
group.invalidate();
}
}
/** * Make the badge visible in the UI. * */
public void show() {
show(false, null);
}
/** * Make the badge visible in the UI. * * @param animate flag to apply the default fade-in animation. */
public void show(boolean animate) {
show(animate, fadeIn);
}
/** * Make the badge visible in the UI. * * @param anim Animation to apply to the view when made visible. */
public void show(Animation anim) {
show(true, anim);
}
/** * Make the badge non-visible in the UI. * */
public void hide() {
hide(false, null);
}
/** * Make the badge non-visible in the UI. * * @param animate flag to apply the default fade-out animation. */
public void hide(boolean animate) {
hide(animate, fadeOut);
}
/** * Make the badge non-visible in the UI. * * @param anim Animation to apply to the view when made non-visible. */
public void hide(Animation anim) {
hide(true, anim);
}
/** * Toggle the badge visibility in the UI. * */
public void toggle() {
toggle(false, null, null);
}
/** * Toggle the badge visibility in the UI. * * @param animate flag to apply the default fade-in/out animation. */
public void toggle(boolean animate) {
toggle(animate, fadeIn, fadeOut);
}
/** * Toggle the badge visibility in the UI. * * @param animIn Animation to apply to the view when made visible. * @param animOut Animation to apply to the view when made non-visible. */
public void toggle(Animation animIn, Animation animOut) {
toggle(true, animIn, animOut);
}
private void show(boolean animate, Animation anim) {
if (getBackground() == null) {
if (badgeBg == null) {
badgeBg = getDefaultBackground();
}
setBackgroundDrawable(badgeBg);
}
applyLayoutParams();
if (animate) {
this.startAnimation(anim);
}
this.setVisibility(View.VISIBLE);
isShown = true;
}
private void hide(boolean animate, Animation anim) {
this.setVisibility(View.GONE);
if (animate) {
this.startAnimation(anim);
}
isShown = false;
}
private void toggle(boolean animate, Animation animIn, Animation animOut) {
if (isShown) {
hide(animate && (animOut != null), animOut);
} else {
show(animate && (animIn != null), animIn);
}
}
/** * Increment the numeric badge label. If the current badge label cannot be converted to * an integer value, its label will be set to "0". * * @param offset the increment offset. */
public int increment(int offset) {
CharSequence txt = getText();
int i;
if (txt != null) {
try {
i = Integer.parseInt(txt.toString());
} catch (NumberFormatException e) {
i = 0;
}
} else {
i = 0;
}
i = i + offset;
setText(String.valueOf(i));
return i;
}
/** * Decrement the numeric badge label. If the current badge label cannot be converted to * an integer value, its label will be set to "0". * * @param offset the decrement offset. */
public int decrement(int offset) {
return increment(-offset);
}
private ShapeDrawable getDefaultBackground() {
int r = dipToPixels(DEFAULT_CORNER_RADIUS_DIP);
float[] outerR = new float[] {r, r, r, r, r, r, r, r};
RoundRectShape rr = new RoundRectShape(outerR, null, null);
ShapeDrawable drawable = new ShapeDrawable(rr);
drawable.getPaint().setColor(badgeColor);
return drawable;
}
private void applyLayoutParams() {
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
switch (badgePosition) {
case POSITION_TOP_LEFT:
lp.gravity = Gravity.LEFT | Gravity.TOP;
lp.setMargins(badgeMarginH, badgeMarginV, 0, 0);
break;
case POSITION_TOP_RIGHT:
lp.gravity = Gravity.RIGHT | Gravity.TOP;
lp.setMargins(0, badgeMarginV, badgeMarginH, 0);
break;
case POSITION_BOTTOM_LEFT:
lp.gravity = Gravity.LEFT | Gravity.BOTTOM;
lp.setMargins(badgeMarginH, 0, 0, badgeMarginV);
break;
case POSITION_BOTTOM_RIGHT:
lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;
lp.setMargins(0, 0, badgeMarginH, badgeMarginV);
break;
case POSITION_CENTER:
lp.gravity = Gravity.CENTER;
lp.setMargins(0, 0, 0, 0);
break;
default:
break;
}
setLayoutParams(lp);
}
/** * Returns the target View this badge has been attached to. * */
public View getTarget() {
return target;
}
/** * Is this badge currently visible in the UI? * */
@Override
public boolean isShown() {
return isShown;
}
/** * Returns the positioning of this badge. * * one of POSITION_TOP_LEFT, POSITION_TOP_RIGHT, POSITION_BOTTOM_LEFT, POSITION_BOTTOM_RIGHT, POSTION_CENTER. * */
public int getBadgePosition() {
return badgePosition;
}
/** * Set the positioning of this badge. * * @param layoutPosition one of POSITION_TOP_LEFT, POSITION_TOP_RIGHT, POSITION_BOTTOM_LEFT, POSITION_BOTTOM_RIGHT, POSTION_CENTER. * */
public void setBadgePosition(int layoutPosition) {
this.badgePosition = layoutPosition;
}
/** * Returns the horizontal margin from the target View that is applied to this badge. * */
public int getHorizontalBadgeMargin() {
return badgeMarginH;
}
/** * Returns the vertical margin from the target View that is applied to this badge. * */
public int getVerticalBadgeMargin() {
return badgeMarginV;
}
/** * Set the horizontal/vertical margin from the target View that is applied to this badge. * * @param badgeMargin the margin in pixels. */
public void setBadgeMargin(int badgeMargin) {
this.badgeMarginH = badgeMargin;
this.badgeMarginV = badgeMargin;
}
/** * Set the horizontal/vertical margin from the target View that is applied to this badge. * * @param horizontal margin in pixels. * @param vertical margin in pixels. */
public void setBadgeMargin(int horizontal, int vertical) {
this.badgeMarginH = horizontal;
this.badgeMarginV = vertical;
}
/** * Returns the color value of the badge background. * */
public int getBadgeBackgroundColor() {
return badgeColor;
}
/** * Set the color value of the badge background. * * @param badgeColor the badge background color. */
public void setBadgeBackgroundColor(int badgeColor) {
this.badgeColor = badgeColor;
badgeBg = getDefaultBackground();
}
private int dipToPixels(int dip) {
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, r.getDisplayMetrics());
return (int) px;
}
}
activity_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent">
<ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/product_list" android:minHeight="60dp" android:cacheColorHint="#00000000" ></ListView>
<include layout="@layout/shopping_cart"/>
</RelativeLayout>
product_item:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="48dp" >
<ImageView android:id="@+id/im" android:layout_width="48dp" android:layout_height="48dp" android:src="@drawable/chi2" android:layout_alignParentLeft="true" android:paddingLeft="5dp" />
<Button android:id="@+id/product_buy_btn" android:layout_width="40dp" android:layout_height="48dp" android:layout_alignParentRight="true" android:layout_gravity="center_vertical" android:layout_margin="10dp" android:background="@drawable/buy_bg_shape" android:text="购买" android:textColor="#F8720D" android:textSize="12sp" />
<TextView android:id="@+id/name" android:layout_width="match_parent" android:layout_height="48dp" android:paddingLeft="10dp" android:text="外卖" android:textSize="18sp" android:gravity="center_vertical" android:layout_toLeftOf="@id/product_buy_btn" android:layout_toRightOf="@id/im" />
</RelativeLayout>
shopping_car:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/shopping_cart" android:layout_width="wrap_content" android:layout_height="70dp" android:layout_alignParentBottom="true" android:layout_marginLeft="20dp" android:paddingBottom="22dp" android:gravity="center_vertical" >
<ImageView android:id="@+id/shopping_img_cart" android:layout_width="50dp" android:layout_height="50dp" android:padding="1dp" android:layout_alignParentLeft="true" android:scaleType="centerInside" android:src="@drawable/shopping_cart" />
</RelativeLayout>
效果: