Android: how to use ValueAnimator

Ahmada Beye picture Ahmada Beye · Nov 23, 2015 · Viewed 31.6k times · Source

I want to do a translate animation using this following

public static void move(TextView view){

    ValueAnimator va = ValueAnimator.ofFloat(0f, 3f);
    int mDuration = 3000; //in millis
    va.setDuration(mDuration);
    va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        public void onAnimationUpdate(ValueAnimator animation) {

        }
    });
    va.setRepeatCount(5);
    va.start();
}

But I don't know how to use onAnimationUpdate method.

Can anyone help please?

Answer

Bartek Lipinski picture Bartek Lipinski · Nov 24, 2015

If you really, really, really want to use ValueAnimator for animating translation of the View you can do it this way (finishing your example, assuming you meant translationX; bare in mind that you're animating translation from 0px to 3px, so you probably won't see much difference):

public static void move(final TextView view){
    ValueAnimator va = ValueAnimator.ofFloat(0f, 3f);
    int mDuration = 3000; //in millis
    va.setDuration(mDuration);
    va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        public void onAnimationUpdate(ValueAnimator animation) {
            view.setTranslationX((float)animation.getAnimatedValue());
        }
    });
    va.setRepeatCount(5);
    va.start();
}