Search code examples
androidobjectanimatorandroid-vectordrawable

How to create ObjectAnimator with valueType - pathType programmatically?


I would like to create a ObjectAnimator programmatically that represents this xml -

 <objectAnimator
        android:duration="@integer/eye_anim_duration"
        android:interpolator="@android:interpolator/anticipate_overshoot"
        android:propertyName="pathData"
        android:repeatCount="0"
        android:repeatMode="restart"
        android:valueFrom="@string/big"
        android:valueTo="@string/small"
        android:valueType="pathType"
        />

In similar fashion as I can create a ObjectAnimator for color change -

 ValueAnimator animator = ObjectAnimator.ofInt(vector, "fillColor", getResources().getColor(R.color.light_green), getResources().getColor(R.color.red));
        animator.setDuration(3000);

Solution

  • Using PathAnimatorInflater class and rewriting the setupAnimatorForPath to accept Strings instead TypedArray it is possible. Here is a method that uses this -

    private ObjectAnimator getAnimator(AnimatedVectorDrawable vector, int in, int out, int delay) {
        ObjectAnimator animator = new ObjectAnimator();
        animator.setTarget(vector);
        animator.setPropertyName("pathData");
        TypeEvaluator evaluator = PathAnimatorInflater.setupAnimatorForPath(animator, getResources().getString(in), getResources().getString(out));
        if (evaluator == null) {
            return null;
        }
        animator.setEvaluator(evaluator);
        animator.setRepeatMode(ValueAnimator.REVERSE);
        animator.setDuration(3000);
        animator.setStartDelay(delay);
        return animator;
    }
    

    But to use this with AnimatedVectorDrawable it needs some changes in Vector classes also.