activity activity - 3 months ago 17
Android Question

fade out AlphaAnimation bug on Android > 5.0

The following code is used to fade out a View. It works for Android SDK < 21.

AlphaAnimation animOut = new AlphaAnimation(1, 0); //fromAlpha, toAlpha
animOut.setDuration(500);
animOut.setAnimationListener(new Animation.AnimationListener()
{
public void onAnimationStart(Animation animation){}
public void onAnimationRepeat(Animation animation){}
public void onAnimationEnd(Animation animation)
{
view.setVisibility(View.INVISIBLE);
}
});
view.startAnimation(animOut);


Strangely, it doesn't work as expected for Android 5.0 and above. As soon as animation starts, the animated View becomes invisible immediately.
How can I fix this?

Edit: this bug occurs if AlphaAnimation is started
onAnimationEnd()
of a TranslateAnimation.

Answer

You could use ViewPropertyAnimator.

Should work on newer APIs (12+) and you don't have to bother with setting the visibility of your View.

Something like this (to fade out):

view.animate().alpha(0).setDuration(500).start();

To fade back in, just animate to your initial alpha value:

view.animate().alpha(1).setDuration(500).start();

To add an AnimatorListener, you can call the setListener() method:

view.animate().alpha(0).setDuration(500)
            .setListener(new Animator.AnimatorListener() {

    // ...

}).start();
Comments