androidanimationviewviewpropertyanimator

Multiple ViewPropertyAnimators


Hope I am not duplicating a question here; I couldn't find one about multiple ViewPropertyAnimators. The goal is to have a view animate from y1 to y2 in 8 seconds. Fade in the first second, and then fade out on the last second.

Here is what I have Tried in my Activity's onCreate():

final View animatingView = findViewById(R.id.animateMe);


    animatingView.post(new Runnable() {
        @Override
        public void run() {
            //Translation
            animatingView.setY(0);
            animatingView.animate().translationY(800).setDuration(8000);

            //Fading view in
            animatingView.setAlpha(0f);
            animatingView.animate().alpha(1f).setDuration(1000);

            //Waiting 6 seconds and then fading the view back out
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    animatingView.animate().alpha(0f).setDuration(1000);
                }
            }, 6000);
        }
    });

However, the result is a translation from 0 to 800, and alpha from 0 to 1 all in one second. and then 6 seconds later the view fades out. It looks every time I call View.animate() it returns the same ViewPropertyAnimator. Is there a way I can have multiple of them? I was thinking about animating the view's alpha, nesting the view in a relative layout, and then animating the relative layouts translation. I would rather not go that route if I don't have to. Does anyone know of a better solution?


Solution

  • You can solve this by using ObjectAnimator instances directly, rather than using the .animate() abstraction.

    ObjectAnimator translationY = ObjectAnimator.ofFloat(animatingView, "translationY", 0f, 800f);
    translationY.setDuration(8000);
    
    ObjectAnimator alpha1 = ObjectAnimator.ofFloat(animatingView, "alpha", 0f, 1f);
    alpha1.setDuration(1000);
    
    ObjectAnimator alpha2 = ObjectAnimator.ofFloat(animatingView, "alpha", 1f, 0f);
    alpha2.setDuration(1000);
    alpha2.setStartDelay(7000);
    
    AnimatorSet set = new AnimatorSet();
    set.playTogether(translationY, alpha1, alpha2);
    set.start();