Android布局背景透明度

23

嗨,我有一个布局,用于填充我的页面,并且我必须在该布局中设置保存在我的“drawable文件夹”中的背景图像。

然后,我想将图像的alpha值设置为相当低,几乎使图像像水印一样。

我的xml如下所示

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/background"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/main_background" >

正如你所看到的,我给布局分配了一个id

我想在我的oncreate方法中能这样做?

View backgroundimage = (View) findViewById(R.id.background);
backgroundimage.setAlpha(80);

这不起作用,然而我怀疑是因为我试图将背景转换为View,应该转换成什么?

4个回答

46

尝试使用:

Drawable.setAlpha();

您应该像这样做:

View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(80);

2
尽管这种方法是有效的,但似乎要获得原始状态或100%的不透明度,您可能需要使用0-1000的比例尺。因此,如果您试图使按钮看起来具有50%的不透明度,您实际上可能需要设置setAlpha(200)而不是setAlpha(50)...至少在API 19上使用Button时...所以要将按钮重置回其原始外观,我必须设置setAlpha(1000)... - whyoz
4
100%不透明度等同于255,而不是1000。 - snapix
因为计算255的%值非常方便! - hmac
当您检查setAlpha()方法时,它的参数带有范围注释:@IntRange(from=0,to=255) int alpha - Micer

36

如果您想在XML中设置alpha值,则可以尝试以下方法:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#CC000000" >

前两位用于设置透明度,这里透明度为 80%,接下来的6位是颜色代码。

因此,透明度使用十六进制编码。FF = 100%,00 = 0%,因此80%在十六进制中不是80,更多标准值请参见此帖子


2

在你的LinearLayout上应用这个:

android:background="#92000000"


2
你可以设置Drawable的透明度,而不是视图!你可以将背景作为Drawable获取并按如下方式操作:
View backgroundimage = (View) findViewById(R.id.background);
backgroundimage.getBackground().setAlpha(80);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接