Fade in image with ViewPropertyAnimator

542 Views Asked by At

I'm trying to fade in an ImageView with a variable duration using ViewPropertyAnimator, but I can't get it to work.

This is code I use for fade out and it works great:

final ImageView imageView = (ImageView)mView.findViewById(R.id.image_view);
Picasso.with(mView.getContext()).load(mItem.thumbnailURL).into(imageView, new Callback() {
      @Override
      public void onSuccess() {
           imageView.animate().alpha(0).setDuration(duration).start();
      }
      ...
});

but if I try to reverse the direction for a fade in, the image never shows up:

final ImageView imageView = (ImageView)mView.findViewById(R.id.image_view);
imageView.setAlpha(0);

Picasso.with(mView.getContext()).load(mItem.thumbnailURL).into(imageView, new Callback() {
      @Override
      public void onSuccess() {
           imageView.animate().alpha(1).setDuration(duration).start();
      }
      ...
});

Why does the alpha value never increase? Is the animation running on a different alpha channel than setAlpha?

2

There are 2 best solutions below

1
Artur  Dumchev On BEST ANSWER

Change deprecated "setAlpha(int alpha)" to "setAlpha (float alpha)", and it will work

imageView.setAlpha(0f);
0
Rico On

Use View.setAlpha(), and the following codes may help you to figure it out.

Trace the source code in ViewPropertyAnimator:

public ViewPropertyAnimator alpha(float value) {
    *animateProperty(ALPHA, value);*
    ...
}

Then,

private void animateProperty(int constantName, float toValue) {
    float fromValue = *getValue(constantName)*;
    ...
}

That's it,

private float getValue(int propertyConstant) {
    final RenderNode node = mView.mRenderNode;
    switch (propertyConstant) {
        ...
        case ALPHA:
            return *mView.mTransformationInfo.mAlpha;*
    }
    return 0;
}

There's something to do with View.setAlpha():

public void setAlpha(@FloatRange(float alpha) {
    ensureTransformationInfo();
    if (mTransformationInfo.mAlpha != alpha) {
        *setAlphaInternal(alpha);*
        ...
    }
}

The same attribute as ViewPropertyAnimator.getValue() referred:

private void setAlphaInternal(float alpha) {
    float oldAlpha = mTransformationInfo.mAlpha;
    *mTransformationInfo.mAlpha = alpha;*
    ...
}