23

Hi I have a layout which I'm using to fill my page and I have to set a background image held in my drawable folder in that layout.

I want to then set the alpha value of the image to something quite low almost make the image like a water mark.

my xml looks like

<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" >

As you can see I have assigned an id to the layout

I thought in my oncreate I could do something like this?

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

This is not working however I suspect its because I'm trying to cast the background as a View what should I cast it as?

Kaushik
  • 6,150
  • 5
  • 39
  • 54
user1096447
  • 429
  • 1
  • 7
  • 22

4 Answers4

46

Try to use:

Drawable.setAlpha();

You should do something like this:

View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(80);
e-shfiyut
  • 3,538
  • 2
  • 30
  • 31
Tang Ke
  • 1,508
  • 12
  • 12
  • 2
    Although this method works, it appears that to get the original state or 100% alpha, you might need to use a 0-1000 scale. So if you are trying to get a button to look 50% alpha, you might actually have to setAlpha(200) instead of setAlpha(50)...at least using API 19 on a Button...so resetting the button back to it's original look, I had to setAlpha(1000)... – whyoz Jan 30 '14 at 02:01
  • 4
    100% opacity equals to 255, not 1000 – snapix Oct 15 '14 at 08:54
  • because it's so convenient to calculate a % of 255! – hmac Jan 02 '19 at 16:42
  • When you check `setAlpha()` method, it's parameter is annotated with range: `@IntRange(from=0,to=255) int alpha`. – Micer Aug 15 '19 at 08:28
36

If you want to set alpha in xml then u can try this:

<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" >

first 2 digits are used to set alpha here alpha is 80% next 6 digits for color code

Hence, alpha is set in hexadecimal coding. FF = 100% and 00 = 0%, thus 80% is not 80 in hexadecimal, for more standard values see this post.

thehennyy
  • 4,020
  • 1
  • 22
  • 31
Kaushik
  • 6,150
  • 5
  • 39
  • 54
2

You Can Set Alpha for Drawables not Views ! You Can get background as a drawable and do like this :

View backgroundimage = (View) findViewById(R.id.background);
backgroundimage.getBackground().setAlpha(80);
Erfan Bagheri
  • 638
  • 1
  • 8
  • 16
2

Use This on your LinearLayout

android:background="#92000000"

Serdar KUŞ
  • 404
  • 1
  • 4
  • 16