Java – Android – getAlpha() from Animation View

Android – getAlpha() from Animation View… here is a solution to the problem.

Android – getAlpha() from Animation View

I have an animation like this:

Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new DecelerateInterpolator());
fadeOut.setDuration(350);
myView.startAnimation(fadeOut);

I’m trying to get its alpha: during the animation

System.out.println(myView.getAlpha());

However, it always returns “1.0” throughout the animation. How do I get myView's actual alpha value during animation?

Solution

By using Transformation with AlphaAnimation, you can retrieve alpha values directly from the AlphaAnimation object instead of viewing them.

Use the purpose of the transform:

Defines the transformation to be applied at one point in time of an Animation.


Steps:

  1. Create a new Transformation.java class, such as https://sourcegraph.com/android.googlesource.com/platform/frameworks/base/-/blob/core/java/android/view/animation/Transformation.java shown

  2. Initialize a Transformation object:

    private Transformation myTransformation;
    mTransformation = new Transformation();
    
  3. Use your code:

    Animation fadeOut = new AlphaAnimation(1, 0);
    fadeOut.setInterpolator(new DecelerateInterpolator());
    fadeOut.setDuration(350);
    
  4. Gets the time (in milliseconds) when the View hierarchy started drawing

    final long time = myView.getDrawingTime();
    
  5. Gets the transformation to apply at a specified point in time. Finally, get the actual alpha value during the animation:

    fadeOut.getTransformation(time, myTransformation);
    final float myAlphaValue = myTransformation.getAlpha();
    

Resources:
https://sourcegraph.com/android.googlesource.com/platform/frameworks/base/-/blob/core/java/android/widget/ProgressBar.java#L1699
https://developer.android.com/reference/android/view/animation/Animation.html
https://developer.android.com/reference/android/view/animation/Transformation.html

Related Problems and Solutions