androidanimation

Fade In Fade Out Android Animation in Java


I want to have a 2 second animation of an ImageView that spends 1000ms fading in and then 1000ms fading out.

Here's what I have so far in my ImageView constructor:

Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setDuration(1000);

Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setStartOffset(1000);
fadeOut.setDuration(1000);

AnimationSet animation = new AnimationSet(true);
animation.addAnimation(fadeIn);
animation.addAnimation(fadeOut);
this.setAnimation(animation);

When I run that animation, nothing shows up. However, when I remove one of the alpha animations, the behavior works as expected.

Things I have already tried:


Solution

  • Figured out my own problem. The solution ended up being based in interpolators.

    Animation fadeIn = new AlphaAnimation(0, 1);
    fadeIn.setInterpolator(new DecelerateInterpolator()); //add this
    fadeIn.setDuration(1000);
    
    Animation fadeOut = new AlphaAnimation(1, 0);
    fadeOut.setInterpolator(new AccelerateInterpolator()); //and this
    fadeOut.setStartOffset(1000);
    fadeOut.setDuration(1000);
    
    AnimationSet animation = new AnimationSet(false); //change to false
    animation.addAnimation(fadeIn);
    animation.addAnimation(fadeOut);
    this.setAnimation(animation);
    


    If you are using Kotlin

    val fadeIn = AlphaAnimation(0f, 1f)
    fadeIn.interpolator = DecelerateInterpolator() //add this
    fadeIn.duration = 1000
    
    val fadeOut = AlphaAnimation(1f, 0f)
    fadeOut.interpolator = AccelerateInterpolator() //and this
    fadeOut.startOffset = 1000
    fadeOut.duration = 1000
    
    val animation = AnimationSet(false) //change to false
    animation.addAnimation(fadeIn)
    animation.addAnimation(fadeOut)
    this.setAnimation(animation)