gpt4 book ai didi

Android Progressbar(自定义 View )值动画不起作用-无效后 View 中的对象动画器

转载 作者:搜寻专家 更新时间:2023-11-01 08:47:19 25 4
gpt4 key购买 nike

我需要在 value 属性更改时为进度条值设置动画,我的自定义 View 如下所示,

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);
}
}

但是动画不工作,我是不是错过了什么,或者我可以做不同的事情吗?

最佳答案

您需要两个函数而不是这个函数。一个函数应该用你的值的新目标调用,另一个函数应该用来实现每个步骤。在第一个中使用 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);
}

一些注意事项:

  • 您不需要调用“setTarget(this)”,因为您已经在 ofFloat 的第一个参数中将 this 设置为目标。
  • 您可能希望延迟设置字段“值”,直到动画完成。您可以使用 AnimationListener 覆盖 onAnimationEnd 来执行此操作。实际上,该字段将在 UI 显示之前设置为新的目标值。
  • “setValue”的签名必须与显示的完全一致,因为这就是 ObjectAnimator.ofFloat 的工作原理:它查找指定属性的 setter,该属性采用 float 并返回 void。

编辑

啊,我明白了,您正在制作自己的进度条。在那种情况下,您调用 invalidate 是正确的,因为您正在覆盖 onDraw。我修改了上面的答案,将“setTargetValue”更改为“setProgress”。这是一个只能从此类外部调用的函数——无论谁知道进展情况。您不希望 setProgress 调用 setValue,反之亦然。

新笔记:

  • 你应该只在任何地方使用浮点值而不是 double 值,因为它们最终会在 RectF 中使用。如果您在数字后添加“f”,Java 会将其解释为 float 而不是 double ,并且您不必在方程式中进行转换。
  • 由于您覆盖了 onDraw,您的中间 setValue 函数只需要设置您的字段“值”,并使进度条无效。

关于Android Progressbar(自定义 View )值动画不起作用-无效后 View 中的对象动画器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26902066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com