安卓代碼實作直播禮物數量放大動畫特效功能
直播禮物數量放大動畫特效功能如下示範:
代碼實作内容如下:
/***
* 初始化界面布局
*/
private void init() {
setOrientation(VERTICAL);
setVisibility(INVISIBLE);
LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
setLayoutParams(lp);
View convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_gift_message,null,false);
avatar = (ImageView) convertView.findViewById(R.id.avatar);
giftIv = (ImageView) convertView.findViewById(R.id.gift_type);
name = (TextView) convertView.findViewById(R.id.name);
giftName = (TextView) convertView.findViewById(R.id.gift_name);
giftNumTv = (TextView) convertView.findViewById(R.id.gift_num);
addView(convertView);
}
/***
* 設定對應的動畫重新整理
* @param gift
*/
public void setGift(Gift gift) {
this.gift = gift;
refreshView();
}
/**
* 設定禮物數量放大和複原的View
* @param view
* @param duration
*/
public void scaleView(View view,long duration){
AnimatorSet animatorSet = new AnimatorSet();//組合動畫
ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 2f, 1f);
ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 2f, 1f);
animatorSet.setDuration(duration);
animatorSet.setInterpolator(new LinearInterpolator());
animatorSet.play(scaleY).with(scaleX);//兩個動畫同時開始
animatorSet.start();
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if (onAnimatorListener!=null){
onAnimatorListener.onAnimationEnd(gift);
}
}
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
if (onAnimatorListener!=null){
onAnimatorListener.onAnimationStart(animation);
}
}
});
}
/**
* 重新整理view
*/
public void refreshView(){
if (gift==null){
return;
}
giftNum = gift.num ;
if (!TextUtils.isEmpty(gift.img)){
Glide.with(getContext()).load(gift.img).placeholder(R.drawable.default_head).into(avatar);
}else {
avatar.setImageResource(R.drawable.default_head);
}
name.setText(gift.name);
giftName.setText(gift.giftName);
giftNumTv.setText("x"+gift.num);
giftIv.setImageResource(gift.giftType);
scaleView(giftNumTv,200);
}
/**
* 連續點選送禮物的時候數字累加縮放效果
* @param num
*/
public void addNum(int num){
giftNum += num ;
giftNumTv.setText("x"+giftNum);
scaleView(giftNumTv,200);
handler.removeCallbacks(runnable);
if (!isShow()){
show();
}
handler.postDelayed(runnable, 3000);
}
Handler handler=new Handler();
Runnable runnable=new Runnable() {
@Override
public void run() {
isShow = false ;
giftNum = 0;
setVisibility(INVISIBLE);
}
};
Handler handler=new Handler();
Runnable runnable=new Runnable() {
@Override
public void run() {
isShow = false ;
giftNum = 0;
setVisibility(INVISIBLE);
}
};
/**
* 顯示view,并開啟定時器
*/
public void show(){
isShow = true ;
setVisibility(VISIBLE);
handler.postDelayed(runnable, 3000);
}