Skip to content

Commit 0ac1829

Browse files
committedSep 10, 2017
优化:及时释放属性动画资源
增加了取消属性动画的方法:cancel(); 在新的配置应用时(apply)、在控件不可见时(onDetachedFromWindow)会调用,防止内存泄漏
1 parent 9a78e7f commit 0ac1829

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed
 

‎src/main/java/com/example/ccy/bounceballview/BounceBallView.java

+23-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import android.animation.Animator;
44
import android.animation.AnimatorListenerAdapter;
5-
import android.animation.ObjectAnimator;
65
import android.animation.ValueAnimator;
76
import android.content.Context;
87
import android.content.res.TypedArray;
@@ -76,8 +75,6 @@ public class BounceBallView extends View {
7675
private Interpolator physicInterpolator; //物理效果插值器
7776
private ValueAnimator[] translateAnim; // 作用与小球位置变换
7877
private float[] translateFraction; //动画比例 [0,1]
79-
private ObjectAnimator[] toAlphaAnim;//作用于画笔从不透明到透明
80-
private ObjectAnimator[] fromAlphaAnim;//做用于画笔从透明到不透明
8178
MultiDecelerateAccelerateInterpolator interCreater;
8279
private Interpolator defaultInterpolator = new LinearInterpolator();
8380

@@ -149,8 +146,6 @@ private void initData() {
149146

150147
translateFraction = new float[ballCount];
151148
translateAnim = new ValueAnimator[ballCount];
152-
toAlphaAnim = new ObjectAnimator[ballCount];
153-
fromAlphaAnim = new ObjectAnimator[ballCount];
154149

155150
}
156151

@@ -440,6 +435,28 @@ private int getRandomColor() {
440435
(int) (255 * Math.random()));
441436
}
442437

438+
/**
439+
* 取消已有动画,释放资源
440+
*/
441+
public void cancel(){
442+
if(translateAnim != null){
443+
for (int i = 0; i < translateAnim.length; i++) {
444+
if(translateAnim[i] != null){
445+
translateAnim[i].cancel();
446+
translateAnim[i] = null;
447+
}
448+
}
449+
translateAnim = null;
450+
}
451+
}
452+
453+
@Override
454+
protected void onDetachedFromWindow() {
455+
// Log.d("ccy","-----------------------------detached");
456+
cancel();
457+
super.onDetachedFromWindow();
458+
}
459+
443460

444461
/*
445462
--------------以下为动态配置、各种setter/getter
@@ -467,6 +484,7 @@ public void apply(){
467484
Log.w(TAG,"调用apply()之前没有调用过config()函数!");
468485
}
469486
isTransaction = false;
487+
cancel();
470488

471489
checkAttrs();
472490
initData();

‎src/main/java/com/example/ccy/bounceballview/MultiDecelerateAccelerateInterpolator.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ public MultiDecelerateAccelerateInterpolator(PointF start,PointF end,float ratio
5252
intervalY = Math.abs(originEnd.y - originStart.y);
5353
bezierControlRatioX = ratiox;
5454
bezierControlRatioY = ratioy;
55-
Log.d("ccy","intervalx,y = " + intervalX + ";" + intervalY);
55+
// Log.d("ccy","intervalx,y = " + intervalX + ";" + intervalY);
5656
}
5757

5858

0 commit comments

Comments
 (0)
Please sign in to comment.