简体   繁体   English

设置布局的Alpha /不透明度

[英]Set Alpha/Opacity of Layout

Is it possible to set and get the Alpha/Opacity of a Layout and all it's child views? 是否可以设置和获取布局的Alpha /不透明度及其所有子视图? 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. 我可以使用动画淡入淡出,但想知道是否有我可以使用的直接方法。

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. 您可以使用带有0持续时间的AlphaAnimation和setFillAfter选项在布局上设置alpha并使用它的子项(或任何其他视图)。

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. 并重新使用reset(),或使用clearAnimation()来删除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. 虽然它看起来很粗糙并且被黑客攻击,但它实际上是一种在set ov视图上设置alpha的好方法,它不需要太多的内存或处理器时间。

Not sure about getting current alpha value though. 不确定是否获得当前的alpha值。

Here is a method that works across all versions ( thanks to @AlexOrlov ): 这是一个适用于所有版本的方法( 感谢@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 ). 显然,对于小于11的API,如果可以,您应该创建一个自定义视图,在绘制其子项之前调用Canvas.saveLayerAlpha()感谢@RomainGuy )。

Alex's solution works but another way is to create a custom view that calls Canvas.saveLayerAlpha() before drawing its children. Alex的解决方案有效,但另一种方法是创建一个自定义视图,在绘制其子项之前调用Canvas.saveLayerAlpha()。 Note that in Android 3.0 there is a new View.setAlpha() API :) 请注意,在Android 3.0中有一个新的View.setAlpha()API :)

现在,您可以使用ViewCompat.setAlpha(View, float)执行此操作。

Sorry for my answer but if you want the alpha you can use the ViewCompat Class 很抱歉我的答案,但如果你想要alpha,你可以使用ViewCompat类

ViewCompat.setAlpha(View view, float alpha) ViewCompat.setAlpha(View view,float alpha)

ViewCompat is in the appcompat v4 ViewCompat位于appcompat v4中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM