26

I was just wondering if there was a way to change the opacity of the background image for a View (ie. TextView, etc.).

I know that I can set the background image like this:

android:background="@drawable/my_drawable_image"

Or I can set a specific background colour with an alpha setting like this:

android:background="#10f7f7f7"

Is there a way I can control the opacity (set the alpha) if I'm setting the background as a drawable image? And I want to do this in the XML Layout. I already know that I could grab the Drawable object and programmatically set the alpha, but I want to see if I can do it in the layout.

xil3
  • 16,305
  • 8
  • 63
  • 97

5 Answers5

35

I ended up just going with the programmatical solution, since it doesn't look like it can be done via the XML layouts.

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);
xil3
  • 16,305
  • 8
  • 63
  • 97
16

This might make your Work simpler

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

Alpha Values 0-255, 0 means fully transparent, and 255 means fully opaque

from: This Answer

Community
  • 1
  • 1
Thamilan S
  • 1,045
  • 3
  • 18
  • 30
9

You can also use XML to change the transparency:

android:alpha = "0.7"

The value of alpha ranges from 0 to 1

Alireza
  • 1,018
  • 1
  • 8
  • 23
7

You can embed the image in xml, so you'll be able to see it in the Graphical Layout

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

And change the code like this to make it transparent:

Drawable loginActivityBackground = findViewById(R.id.login_layout).getBackground();
loginActivityBackground.setAlpha(127);
Axe
  • 6,285
  • 3
  • 31
  • 38
Shlomi Hasin
  • 443
  • 7
  • 12
2

The answer you gave didn't exactly answer the question you asked. Here's what I did.

    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);
JohnnyLambada
  • 12,700
  • 11
  • 57
  • 61
  • Well, my question was if it could be set within the XML Layout, rather than programmatically. – xil3 Mar 13 '12 at 19:25