03.3 精通自定义 View 之属性动画——ofObject

返回自定义 View 目录

1
public static ValueAnimator ofObject(TypeEvaluator evaluator, Object... values)

3.3.1 示例:字母从 A 变化到 Z

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private void startAnim() {
ValueAnimator animator = ValueAnimator.ofObject(new CharEvaluator(),
Character.valueOf('A'), Character.valueOf('Z'));
animator.setDuration(3000);
animator.setInterpolator(new AccelerateInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
char text = (Character) animation.getAnimatedValue();
mView.setText(String.valueOf(text));
}
});
animator.start();
}
public class CharEvaluator implements TypeEvaluator<Character> {
@Override
public Character evaluate(float fraction,Character startValue,Character endValue){
int startInt = (int) startValue;
int endInt = (int) endValue;
int value = (int) (startInt + fraction * (endInt - startInt));
return (char) value;
}
}

3.3.2 示例:抛物动画

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private void startAnim() {
ValueAnimator animator = ValueAnimator.ofObject(new FallingBallEvaluator(),
new Point(0, mTop), new Point(500, 500));
animator.setDuration(3000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Point p = (Point) animation.getAnimatedValue();
mView.layout(p.x, p.y, p.x + mView.getWidth(), p.y + mView.getHeight());
}
});
animator.start();
}
public class FallingBallEvaluator implements TypeEvaluator<Point> {
private Point point = new Point();
@Override
public Point evaluate(float fraction, Point startValue, Point endValue) {
point.x = (int)(startValue.x + fraction * (endValue.x - startValue.x));
if (fraction * 2 < 1) {
point.y = (int)(startValue.y + fraction * 2 * (endValue.y - startValue.y));
} else {
point.y = endValue.y;
}
return point;
}
}