自定义控件中使用动画
package de.bvb.widget; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import android.view.animation.AnticipateInterpolator; /** * 自定义控件 动画 */ public class RecView extends View { private Paint paint; private int measuredHeight; private int measuredWidth; private ValueAnimator valueAnimator; public RecView(Context context) { this(context, null); } public RecView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RecView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); paint = new Paint(); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.parseColor("#ff0000")); valueAnimator = ValueAnimator.ofFloat(0, 0); } float scale; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); measuredHeight = getMeasuredHeight(); measuredWidth = getMeasuredWidth(); } @Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); canvas.drawRect(0, 0, scale * measuredWidth, measuredHeight, paint); } /** * 页面调用事件 * @param scale 填充的进度 * @param hasAnimator 是否使用动画 */ public void setScale(float scale, boolean hasAnimator) { this.scale = scale; if (!hasAnimator) { invalidate(); } else if (hasAnimator && !valueAnimator.isRunning()) { startAnimator(); } } private void startAnimator() { valueAnimator = ValueAnimator.ofFloat(0, scale); valueAnimator.setDuration(5000); valueAnimator.setInterpolator(new AnticipateInterpolator()); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { RecView.this.scale = Float.parseFloat(animation.getAnimatedValue().toString()); invalidate(); } }); valueAnimator.start(); } }