Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating drawable alpha property

I want to animate the alpha property of a ViewGroup's background Drawable.

I get a reference to the background's drawable using view.getBackground().

Then I use the following code (from this thread):

    if (backgroundDrawable.getAlpha() == 0) {
            ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(backgroundDrawable, PropertyValuesHolder.ofInt("alpha", 255));
            animator.setTarget(backgroundDrawable);
            animator.setDuration(2000);
            animator.start();
        } else {
            ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(backgroundDrawable, PropertyValuesHolder.ofInt("alpha", 0));
            animator.setTarget(backgroundDrawable);
            animator.setDuration(2000);
            animator.start();
        }

But the animation always starts from the alpha value 0. (meaning, when I want to animate to 0, it disappears immediately, because it animates from 0 to 0).

Does anyone know how I can make this work?

like image 572
dors Avatar asked Mar 02 '15 09:03

dors


People also ask

What is Alpha in animate?

transparency is called the alpha property in animate (with an alpha = 0 being transparent and an alpha =1 being fully opaque).

What are the two different types of view animations property animation and tween animation?

These three types of animation fall into two categories: frame animations and tweened animations. Unsurprisingly, frame-base animations are a type of frame animation, whereas View- and Property-based animations are types of tweened animations.

Which category of animations allow you to animate an object properties?

The property animation system is a robust framework that allows you to animate almost anything. You can define an animation to change any object property over time, regardless of whether it draws to the screen or not.


1 Answers

I believe what u want is to set initial and final values for your animations, and not just the final value, like this:

if (backgroundDrawable.getAlpha() == 0) {
        ObjectAnimator animator = ObjectAnimator
            .ofPropertyValuesHolder(backgroundDrawable, 
                      PropertyValuesHolder.ofInt("alpha", 0, 255));
        animator.setTarget(backgroundDrawable);
        animator.setDuration(2000);
        animator.start();
    } else {
        ObjectAnimator animator = ObjectAnimator
             .ofPropertyValuesHolder(backgroundDrawable, 
                       PropertyValuesHolder.ofInt("alpha", 255, 0));
        animator.setTarget(backgroundDrawable);
        animator.setDuration(2000);
        animator.start();
    }

alternatively, starting from the current value using drawable.getAlpha(), but that method is only available starting on API 19 =/

like image 84
Budius Avatar answered Oct 05 '22 23:10

Budius