Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Alpha/Opacity of Layout

Tags:

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.

like image 887
Tsuma-Shifu Avatar asked Jan 27 '11 08:01

Tsuma-Shifu


People also ask

How do you set up Alpha?

To get α subtract your confidence level from 1. For example, if you want to be 95 percent confident that your analysis is correct, the alpha level would be 1 – . 95 = 5 percent, assuming you had a one tailed test. For two-tailed tests, divide the alpha level by 2.

How do you change opacity on Android?

setAlpha(51); Here you can set the opacity between 0 (fully transparent) to 255 (completely opaque). The 51 is exactly the 20% you want.

What is Alpha in XML?

"alpha" is used to specify the opacity for an image.


2 Answers

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.

like image 70
Alex Orlov Avatar answered Oct 11 '22 07:10

Alex Orlov


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).

like image 40
Takhion Avatar answered Oct 11 '22 06:10

Takhion