androidanimationobjectanimator

ObjectAnimator with array variable


I'm building a custom view contains three progress bars, therefore I have an array variable, like this one:

float[] progress = new float[3];

And I want to update specific progress entry using 'ObjectAnimator'; here are the relevant methods:

public void setProgress(int index, float progress) {
    this.progress[index] = (progress<=100) ? progress : 100;
    invalidate();
}

public void setProgressWithAnimation(int index, float progress, int duration) {
    PropertyValuesHolder indexValue = PropertyValuesHolder.ofInt("progress", index);
    PropertyValuesHolder progressValue = PropertyValuesHolder.ofFloat("progress", progress);

    ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(this, indexValue, progressValue);
    objectAnimator.setDuration(duration);
    objectAnimator.setInterpolator(new DecelerateInterpolator());
    objectAnimator.start();
}

but I'm getting this warning: Method setProgress() with type int not found on target class

I also tried with setter contains an array (setProgress (float[] progress)) but still got an error:

Method setProgress() with type float not found on target class

How can I use array variable in ObjectAnimator?


Solution

  • After a lot of attempts, it's looks like it's possible to do this using ObjectAnimator. I also found this in the doc:

    The object property that you are animating must have a setter function (in camel case) in the form of set(). Because the ObjectAnimator automatically updates the property during animation, it must be able to access the property with this setter method. For example, if the property name is foo, you need to have a setFoo() method. If this setter method does not exist, you have three options:

    • Add the setter method to the class if you have the rights to do so.

    • Use a wrapper class that you have rights to change and have that wrapper receive the value with a valid setter method and forward it to the original object.

    • Use ValueAnimator instead.

    As Google advice, I tried with ValueAnimator and it's works fine:

    public void setProgressWithAnimation(float progress, int duration, final int index) {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(progress);
        valueAnimator.setDuration(duration);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                setProgress((Float) valueAnimator.getAnimatedValue(), index);
            }
        });
        valueAnimator.start();
    }