2011-02-11 55 views
20

我只是想知道是否有方法来更改背景图像的不透明度为View(即TextView等)。背景上的不透明度在视图中的可绘制图像(使用XML布局)

我知道我可以这样设置背景图片:

android:background="@drawable/my_drawable_image" 

或者,我可以设置有一个Alpha设置这样一个特定的背景色:

android:background="#10f7f7f7" 

有没有一种方法,我可以控制不透明度(设置alpha)如果我将背景设置为可绘制图像?我想在XML布局中执行此操作。我已经知道我可以抓住Drawable对象并以编程方式设置alpha,但我想看看我能否在布局中做到这一点。

+1

它可以使用drawable xml资源完成。看看我的答案http://stackoverflow.com/a/36467846/5460053 – 2016-04-07 06:04:03

回答

29

我最终只用了编程解决方案,因为它看起来不像是通过XML布局完成的。

Drawable rightArrow = getResources().getDrawable(R.drawable.green_arrow_right_small); 

// setting the opacity (alpha) 
rightArrow.setAlpha(10); 

// setting the images on the ImageViews 
rightImage.setImageDrawable(rightArrow); 
+0

@mohammadsadeghsaati`#setAlpha(int)`可用于API Draw Level 1在`Drawable`上。 – 2015-05-08 07:50:51

2

你给没有完全回答你问的问题的答案。这就是我所做的。

Drawable login_activity_top_background = getResources().getDrawable(R.drawable.login_activity_top_background); 
    login_activity_top_background.setAlpha(127); 
    LinearLayout login_activity_top = (LinearLayout) findViewById(R.id.login_activity_top); 
    login_activity_top.setBackgroundDrawable(login_activity_top_background); 
+0

那么,我的问题是,如果它可以在XML布局,而不是编程设置。 – xil3 2012-03-13 19:25:39

12

这可能使您的工作更简单

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

alpha值0-255,0表示完全透明,255表示完全不透明

来自:This Answer

5

您可以嵌入在xml中的图像,所以你将能够看到它在图形布局

<LinearLayout 
     style="@style/LoginFormContainer" 
     android:id="@+id/login_layout" 
     android:orientation="vertical" 
     android:background="@drawable/signuphead"> 

并改变这样的代码,使之透明:

Drawable loginActivityBackground = findViewById(R.id.login_layout).getBackground(); 
loginActivityBackground.setAlpha(127); 
7

您还可以使用XML来改变透明度:

android:alpha = "0.7"

阿尔法的取值范围从0到1

+0

无法使用imageButton – 2016-08-09 08:21:47