我需要在value
属性更改时更改动画进度条值,我的自定义视图如下所示,
public class ProgressBar extends View {
public ProgressBar(Context context) {
this(context, null);
}
public ProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
ObjectAnimator animator;
double value = 50;
public double getValue() {
return value;
}
public void setTargetValue(double targetValue) {
animator = ObjectAnimator.ofFloat(this, "value", (float) this.value,(float) targetValue);
animator.setDuration(1500);
animator.start();
this.value = targetValue;
}
public void setValue(double tempValue) {
setTargetValue(tempValue);
this.invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStrokeWidth(3);
RectF borderRectF = new RectF(50,100,400,200);
RectF backgroundRectF = new RectF(53,103,397,197);
RectF filledRectF = new RectF(53,103,53,197);
paint.setColor(Color.LTGRAY);
canvas.drawRect(borderRectF, paint);
paint.setStrokeWidth(0);
paint.setColor(Color.WHITE);
canvas.drawRect(backgroundRectF, paint);
paint.setColor(Color.BLUE);
filledRectF = getfilledRect();
canvas.drawRect(filledRectF, paint);
}
private RectF getfilledRect(){
float filledValue = (float)(53+(3.44 * this.value));
filledValue = Math.min(filledValue,397);
return new RectF(53,103,filledValue,197);
}
}
但是动画无效,我想念一下,还是我可以做不同的事情?
答案 0 :(得分:3)
您需要两个功能而不是这个功能。应该使用新目标为您的值调用一个函数,并且应该使用另一个函数来实现每个步骤。在第一个中使用ObjectAnimator,它将为每个增量步骤多次调用第二个函数。像这样:
public void setProgress(float progress) {
animator = ObjectAnimator.ofFloat(this, "value", this.value, progress);
animator.setDuration(1500);
animator.start();
}
public void setValue(float value) {
this.value = value;
invalidate();
}
private RectF getfilledRect() {
float filledValue = 53f + (3.44f * this.value);
filledValue = Math.min(filledValue, 397f);
return new RectF(53f, 103f, filledValue, 197f);
}
一些注意事项:
修改
啊,我明白了,你正在制作自己的进度条。在这种情况下,您调用invalidate是正确的,因为您要覆盖onDraw。我修改了上面的答案,将“setTargetValue”更改为“setProgress”。这个函数只能从OUTSIDE这个类调用 - 谁知道进展是什么。您不希望setProgress调用setValue,反之亦然。
新笔记: