Jaythaking
Jaythaking

Reputation: 2102

Fade in not working but fade out Animation works on Android

I use this method to show any view that need a fade in or a fade out Animation.

It works perfectly when I pass false to execute the fade out animation but when I pass true, the fade in doesn't execute, instead, It just appears after 500ms without animation;

private void setViewTransition(final boolean isVisible, final View view) {

    Animation fadeAnim;

    if (isVisible) {
        fadeAnim = new AlphaAnimation(0.0f, 1.0f);
        if (view.getAlpha() == 1.0f) {
            return;
        }
    } else {
        fadeAnim = new AlphaAnimation(1.0f, 0.0f);
        if (view.getAlpha() == 0.0f) {
            return;
        }
    }

    fadeAnim.setDuration(500);
    fadeAnim.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            if (isVisible) {
                view.setAlpha(1.0f);
            } else {
                view.setAlpha(0.0f);
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    });

    view.startAnimation(fadeAnim);
}

It might be related to that issue: Android fade in not working which never got any answers...

What am I doing wrong ?

Upvotes: 0

Views: 1129

Answers (1)

Brian
Brian

Reputation: 8085

Although I'm not entirely sure why your way doesn't work. It is a bit roundabout and is probably more complicated than it needs to be to get a fade animation. Here's a really concise way of doing it instead (for API 12+).

private void setViewTransition(boolean isVisible, View view) {
    view.animate().alpha(isVisible ? 1.0f : 0.0f).setDuration(500);
}

Upvotes: 3

Related Questions