Android doesn't animate alpha if it's initially zero

Can Poyrazoğlu picture Can Poyrazoğlu · Apr 6, 2015 · Viewed 11.1k times · Source

I am trying to animate alpha of an Android view (two animations, both fade in and fade out). It all works fine if the view's alpha is initially 1, by default. However, I want that view to be transparent initially, hence I've set it's alpha to zero:

indicatorContainer.setAlpha(0);

Now, the animations won't work. It will never become visible. If I comment out that line, the view is initially displayed (which I don't want), but my animations works fine when I invoke them. I though it's something trivial but apparently it's not. What am I doing wrong?

UPDATE: I've also tried a floating point 0f instead of integer 0 after reading some API changes involving the setAlpha method, thinking that my call may be calling the incorrect overload, but nothing changed.

Answer

Nikhil Verma picture Nikhil Verma · Apr 6, 2015

Try something like this:

  mRelativeLayout.setAlpha(0f);
    mRelativeLayout.animate().alpha(1f).setDuration(500).setListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            mRelativeLayout.setVisibility(View.VISIBLE);
            //OR
            mRelativeLayout.setAlpha(1f);
        }
    });