20

Is it possible to set and get the Alpha/Opacity of a Layout and all it's child views? I'm not talking about the background. Say a collection of Video Controls like Play, Pause and Progressbar in a Relative Layout.

I can use animation to fade in and out but wanted to know if there was a direct method I could use.

Tsuma-Shifu
  • 283
  • 1
  • 4
  • 9

5 Answers5

60

You can set the alpha on the layout and it's children (or any other view for that matter) using AlphaAnimation with 0 duration and setFillAfter option.

Example:

AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F);
alpha.setDuration(0); // Make animation instant
alpha.setFillAfter(true); // Tell it to persist after the animation ends
// And then on your layout
yourLayout.startAnimation(alpha);

You can use one animation for multiple components to save memory. And do reset() to use again, or clearAnimation() to drop alpha.

Though it looks crude and hacked it's actually a good way to set alpha on set ov views that doesn't take much memory or processor time.

Not sure about getting current alpha value though.

Thierry Roy
  • 8,452
  • 10
  • 60
  • 84
Alex Orlov
  • 18,077
  • 7
  • 55
  • 44
  • Thanks. I was using animation but I was setting the object visibility to gone once the animation had completed instead of using the setFillAfter method. – Tsuma-Shifu Jan 28 '11 at 10:23
  • It seems to break the animations (if run during the animation). Any fix for this? – Sufian Apr 29 '13 at 07:18
  • As a workaround, I used a semi-transparent image set as background of a `View`. – Sufian Apr 29 '13 at 08:19
15

Here is a method that works across all versions (thanks to @AlexOrlov):

@SuppressLint("NewApi")
public static void setAlpha(View view, float alpha)
{
    if (Build.VERSION.SDK_INT < 11)
    {
        final AlphaAnimation animation = new AlphaAnimation(alpha, alpha);
        animation.setDuration(0);
        animation.setFillAfter(true);
        view.startAnimation(animation);
    }
    else view.setAlpha(alpha);
}

Clearly, for API less than 11 if you can you should create a custom view that calls Canvas.saveLayerAlpha() before drawing its children (thanks to @RomainGuy).

Community
  • 1
  • 1
Takhion
  • 2,706
  • 24
  • 30
6

Alex's solution works but another way is to create a custom view that calls Canvas.saveLayerAlpha() before drawing its children. Note that in Android 3.0 there is a new View.setAlpha() API :)

Romain Guy
  • 97,993
  • 18
  • 219
  • 200
3

Now you can use ViewCompat.setAlpha(View, float) for this action.

Pang
  • 9,564
  • 146
  • 81
  • 122
Firstborn
  • 71
  • 2
0

Sorry for my answer but if you want the alpha you can use the ViewCompat Class

ViewCompat.setAlpha(View view, float alpha)

ViewCompat is in the appcompat v4

vincent091
  • 2,325
  • 4
  • 17
  • 21