Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 925
Can Poyrazoğlu Avatar asked Apr 06 '15 14:04

Can Poyrazoğlu


2 Answers

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);
        }
    });
like image 167
Nikhil Verma Avatar answered Oct 12 '22 10:10

Nikhil Verma


I faced same issue where indicatorContainer is ImageButton. Below code fixes this very, very annoying issue...

// XXX: Does not work if just 0. It calls `ImageView#setAlpha(int)` deprecated method.
indicatorContainer.setAlpha(0.0f);
ViewCompat.animate(indicatorContainer).alpha(1);
like image 37
ypresto Avatar answered Oct 12 '22 09:10

ypresto