自定义ViewGroup实现进度动态更新效果,效果图如下:
package com.example.think.myapplication; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.view.animation.AccelerateInterpolator; import android.widget.LinearLayout; /** * 投票进度显示容器 * @author hiphonezhu@gmail.com */ public class VoteGroup extends LinearLayout { private float cProgress; // 当前进度 private Paint mPaint; // 背景色画笔 private long mDuration = 1500; // 动画持续时间 private final int MAX_ALPHA = 155; // 最大透明阀值 private final int MAX_PROGRESS = 100; // 最大进度值 public VoteGroup(Context context) { this(context, null); } public VoteGroup(Context context, AttributeSet attrs) { this(context, attrs, -1); } public VoteGroup(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mPaint = new Paint(); } /** * 设置动画时间 * @param duration 毫秒 */ public void setDuration(int duration) { mDuration = duration; } /** * 非动画显示进度 * @param progress 进度 * @param color 颜色值 */ public void setProgress(float progress, int color) { setProgress(progress, color, false); } /** * 是否使用动画方式显示进度 * @param progress 进度 * @param color 颜色值 * @param animated 是否使用动画 */ public void setProgress(float progress, int color, boolean animated) { mPaint.setColor(color); if (animated) { ValueAnimator animator = ValueAnimator.ofFloat(0f, progress); animator.setDuration(mDuration); animator.setInterpolator(new AccelerateInterpolator()); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { invalidate((float)animation.getAnimatedValue()); } }); animator.start();; } else { invalidate(progress); } } /** * 刷新视图 * @param progress 进度 */ private void invalidate(float progress) { if (progress > MAX_PROGRESS) { progress = MAX_PROGRESS; } cProgress = progress; /** * 设置透明度 * @see #MAX_ALPHA */ int alpha = (int)((cProgress / MAX_PROGRESS) * MAX_ALPHA); mPaint.setAlpha(alpha); invalidate(); } /** * 绘制完children之后根据进度绘制自身 * @param canvas */ @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); canvas.drawRect(0, 0, getMeasuredWidth() * cProgress / MAX_PROGRESS, getMeasuredHeight(), mPaint); } }
编辑:HiphoneZhu