Animate custom object variable

2.2k views Asked by At

Let's say I have a custom object, like a Point class (I am not using the one from Android), and I need to slowly change its coordinates from a start value to an end value when the user double taps the screen. I have already all setup, but I can't get to "animate" this change. Do you know how I can do it?

I have already tried something like this, but got no change: ObjectAnimator(point, "point.variable", final_value).start()

1

There are 1 answers

7
Caleb Rush On BEST ANSWER

You may have set up the ObjectAnimator incorrectly.

Let's assume your Point class has an instance variable xPosition that is an Integer. In order to animate the xPosition with the ObjectAnimator, you would do this:

ObjectAnimator.ofInt(new Point(), // Instance of your class
                     "xPosition", // Name of the property you want to animate
                     startValue, // The initial value of the property
                     ... intermediateValues ..., // Any other desired values
                     endValue) // The final value of the property
    .setDuration(duration) // Make sure to set a duration for the Animator
    .start(); // Make sure to start the animation.

The ObjectAnimator will attempt to update the property automatically after each frame, but in order for it to be successful, your class must have a proper setter method for the property in the format of setYourProperty. So in this particular example, your class must have a method called setXPosition (note the camel case).

If, for some reason, this is not working, then you fall back on a ValueAnimator. You set up the ValueAnimator a similar way.

ValueAnimator anim = ValueAnimator.ofInt(startValue // Initial value of the property
                                         endValue) // Final value of the property
    .setDuration(duration); // Make sure to set a duration for the Animation.

The difference here is that you must manually update your property. To do so, we add an AnimatorUpdateListener to the animation whose onAnimationUpdate method will be called after each frame in the animation.

anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        // Manually call the xPosition's setter method.
        point.setXPosition(animation.getAnimatedValue());
    }
});

And don't forget to start the animation.

anim.start();

For more details regarding ValueAnimator and ObjectAnimator, see Google's API Guide on Property Animation: http://developer.android.com/guide/topics/graphics/prop-animation.html#value-animator