How to Set Opacity (Alpha) for View in Android
Asked Answered
S

13

245

I have a button as in the following:

<Button 
     android:text="Submit" 
     android:id="@+id/Button01" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content">
</Button>

In my onCreate() event, I am calling Button01 like this:

setContentView(R.layout.main);

View Button01 = this.findViewById(R.id.Button01);
Button01.setOnClickListener(this);

There is a background in the application, and I want to set an opacity on this submit button. How can I set an opacity for this view? Is it something that I can set on the java side, or can I set in the main.xml file?

On the java side I tried Button01.mutate().SetAlpha(100), but it gave me an error.

Seibert answered 15/5, 2010 at 3:4 Comment(0)
B
65

I just found your question while having the similar problem with a TextView. I was able to solve it, by extending TextView and overriding onSetAlpha. Maybe you could try something similar with your button:

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class AlphaTextView extends TextView {

  public AlphaTextView(Context context) {
    super(context);
  }

  public AlphaTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public AlphaTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  public boolean onSetAlpha(int alpha) {
    setTextColor(getTextColors().withAlpha(alpha));
    setHintTextColor(getHintTextColors().withAlpha(alpha));
    setLinkTextColor(getLinkTextColors().withAlpha(alpha));
    return true;
  }
}
Biafra answered 25/5, 2010 at 11:52 Comment(2)
Thanks, this also helped me. However it's ridiculous that a TextView and an ImageView have different ways to set alpha.Pillsbury
This helped me too for applying click effect on image view without second resource. Thanx!!Tennies
H
606

I'm amazed by everyone else's MUCH more complicated answers.

XML

You can very simply define the alpha in the color definition of the button (or any other view) in your xml:

android:color="#66FF0000"    // Partially transparent red

In the above example, the color would be a partially transparent red.

When defining the color of a view, the format can be either #RRGGBB or #AARRGGBB, where AA is the hex alpha value. FF would be fully opaque and 00 would be full transparent.

Dynamically

If you need to dynamically alter the opacity in your code, use

myButton.getBackground().setAlpha(128);  // 50% transparent

Where the INT ranges from 0 (fully transparent) to 255 (fully opaque).

Horbal answered 7/10, 2011 at 15:54 Comment(9)
This is still not the solution if you have a compound drawableFeral
Set half transparent green color of view: <RelativeLayout android:background="#8700FF00"/>Eccrinology
View does not have android:color attribute.Feudal
@moshersan You can set the color in the android:background property itself!Covell
What about a three digit value? like Alpha 255?Zephaniah
@HereticMonk Just use a Decimal to Hex conversion tool to determine what Hex value to use. 255 Dec would be FF Hex.Horbal
android:alpha could be another solution from XML.Katharyn
@Dheeraj Bhaskar : Not if the view background is an image. Then the answer holds. bacground <> bg color.Unplumbed
That is incorrect background opacity isn't view opacity. Not equivalent in many use casesClinic
P
228

I guess you may have already found the answer, but if not (and for other developers), you can do it like this:

btnMybutton.getBackground().setAlpha(45);

Here I have set the opacity to 45. You can basically set it from anything between 0(fully transparent) to 255 (completely opaque)

Planetarium answered 1/3, 2011 at 11:29 Comment(6)
This is only available on API 11+ developer.android.com/reference/android/view/…Herringbone
@Herringbone you have linked to the setAlpha method on the View class, but the post is using the setAlpha on the Drawable class. The getBackground method returns a Drawable. This method is from API Level 1. developer.android.com/reference/android/graphics/drawable/…Staciastacie
Oh interesting! I didn't see that. Would this mean that the text was fully visible even if the background was set to transparent.Herringbone
-1 this doesn't work in my case where my background drawable is a selector.Unwise
this works great but with one side effect: i have many buttons sharing the same background and they become all transparent! :(Frequent
@Frequent you are right, do you know any workaround for this side effect? I tried to clone the same background (which is a color res) with a different name, but it didn't work..!?Leeannaleeanne
F
90

Much more easier from the above. Default alpha attribute is there for button

android:alpha="0.5"

The range is between 0 for complete transparent and 1 for complete opacity.

Force answered 14/1, 2016 at 6:50 Comment(1)
When I do this, I get a compile error: "aapt.v2.Aapt2Exception: Android resource linking failed"Wendolynwendt
C
67

What I would suggest you do is create a custom ARGB color in your colors.xml file such as :

<resources>
<color name="translucent_black">#80000000</color>
</resources>

then set your button background to that color :

android:background="@android:color/translucent_black"

Another thing you can do if you want to play around with the shape of the button is to create a Shape drawable resource where you set up the properties what the button should look like :

file: res/drawable/rounded_corner_box.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#80000000"
        android:endColor="#80FFFFFF"
        android:angle="45"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

Then use that as the button background :

    android:background="@drawable/rounded_corner_box"
Canna answered 27/1, 2011 at 22:20 Comment(1)
If you're struggling to covert from 40% opacity to a hex value you can use google search "40% of 255 to hex" gives the hex value for 40%Assize
B
65

I just found your question while having the similar problem with a TextView. I was able to solve it, by extending TextView and overriding onSetAlpha. Maybe you could try something similar with your button:

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class AlphaTextView extends TextView {

  public AlphaTextView(Context context) {
    super(context);
  }

  public AlphaTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public AlphaTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  public boolean onSetAlpha(int alpha) {
    setTextColor(getTextColors().withAlpha(alpha));
    setHintTextColor(getHintTextColors().withAlpha(alpha));
    setLinkTextColor(getLinkTextColors().withAlpha(alpha));
    return true;
  }
}
Biafra answered 25/5, 2010 at 11:52 Comment(2)
Thanks, this also helped me. However it's ridiculous that a TextView and an ImageView have different ways to set alpha.Pillsbury
This helped me too for applying click effect on image view without second resource. Thanx!!Tennies
S
63

According to the android docs view alpha is a value between 0 and 1. So to set it use something like this:

View v;
v.setAlpha(.5f);
Stockwell answered 14/5, 2013 at 5:46 Comment(2)
That's what only worked for me for whole view... I have tried on listview item, which has multiple textviews too. this single line helped to set alpha on view and its children. Thanks @StockwellHerdic
Only thing that worked for me as well. I know this is old, but thanks @StockwellIlocano
W
19
android:background="@android:color/transparent"

The above is something that I know... I think creating a custom button class is the best idea

API Level 11
Recently I came across this android:alpha xml attribute which takes a value between 0 and 1. The corresponding method is setAlpha(float).

Womb answered 15/5, 2010 at 3:31 Comment(3)
Hi Josnidhin. Thank you for your reply. But it makes the whole button completely transparent. What I am looking is putting some opacity (maybe via alpha value) on the button.Seibert
It's a float, so you can use values BETWEEN 0 and 1, 0.5 for instance.Surfboat
@Surfboat - i believe ncakmak meant the first solution. setting @android:color/transparent as Background will indeed make the view completely transparent. The @android:alpha - part seems to be an addendum.Adapa
J
18

Although btnMybutton.getBackground().setAlpha(45); is nice idea, it just apply alpha to background and not the whole view.

If you want apply alpha to view use btnMybutton.setAlpha(0.30f); instead. This apply opacity to View. It accepts a value between 0 and 1.

Doc says:

Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is completely transparent and 1 means the view is completely opaque. If this view overrides onSetAlpha(int) to return true, then this view is responsible for applying the opacity itself. Otherwise, calling this method is equivalent to calling setLayerType(int, android.graphics.Paint) and setting a hardware layer. Note that setting alpha to a translucent value (0 < alpha < 1) may have performance implications. It is generally best to use the alpha property sparingly and transiently, as in the case of fading animations.

Justiciary answered 6/6, 2013 at 6:8 Comment(0)
C
13

For a view you can set opacity by the following.

view_name.setAlpha(float_value);

The property view.setAlpha(int) is deprecated for the API version greater than 11. Henceforth, property like .setAlpha(0.5f) is used.

Counterblast answered 28/12, 2015 at 12:58 Comment(1)
This is the correct answer. Just using height to 1dp makes it look thick.Tarah
F
8

If you use Kotlin , it's very easy to set alpha like this

imageView.alpha= 0.5F

where the value must be a float number.

Ferdinande answered 24/3, 2021 at 13:12 Comment(0)
U
7

I've run into this problem with ICS/JB because the default buttons for the Holo theme consist of images that are slightly transparent. For a background this is especially noticeable.

Gingerbread vs. ICS+:

Gingerbread ICS

Copying over all of the drawable states and images for each resolution and making the transparent images solid is a pain, so I've opted for a dirtier solution: wrap the button in a holder that has a white background. Here's a crude XML drawable (ButtonHolder) which does exactly that:

Your XML file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              style="@style/Content">
  <RelativeLayout style="@style/ButtonHolder">
      <Button android:id="@+id/myButton"
              style="@style/Button"
              android:text="@string/proceed"/>
    </RelativeLayout>
</LinearLayout>

ButtonHolder.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="rectangle">
      <solid android:color="@color/white"/>
    </shape>
  </item>

</layer-list>

styles.xml

.
.
.      
  <style name="ButtonHolder">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:background">@drawable/buttonholder</item>
  </style>

  <style name="Button" parent="@android:style/Widget.Button">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:textStyle">bold</item>
  </style>
.
.
.

However, this results in a white border because the Holo button images include margins to account for the pressed space:

Too much white Too much white pressed

So the solution is to give the white background a margin (4dp worked for me) and rounded corners (2dp) to completely hide the white yet make the button solid:

ButtonHolder.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

  <item>
    <shape android:shape="rectangle">
      <solid android:color="@android:color/transparent"/>
    </shape>
  </item>

  <item android:top="4dp" android:bottom="4dp" android:left="4dp" android:right="4dp">
    <shape android:shape="rectangle">
      <solid android:color="@color/white"/>
      <corners android:radius="2dp" />
    </shape>
  </item>

</layer-list>

The final result looks like this:

No white No white pressed

You should target this style for v14+, and tweak or exclude it for Gingerbread/Honeycomb because their native button image sizes are different from ICS and JB's (e.g. this exact style behind a Gingerbread button results in a small bit of white below the button).

Uintathere answered 21/3, 2013 at 18:33 Comment(0)
S
6

For API < 11 for textView color I did the following:

int textViewColor = textView.getTextColors().getDefaultColor(); 
textView.setTextColor(Color.argb(128, Color.red(textViewColor), Color.green(textViewColor), Color.blue(textViewColor))); //50% transparent

A little cumbersome, but hey, it works :-)

Selfanalysis answered 17/12, 2013 at 21:54 Comment(0)
A
1

I know this already has a bunch of answers but I found that for buttons it is just easiest to create your own .xml selectors and set that to the background of said button. That way you can also change it state when pressed or enabled and so on. Here is a quick snippet of one that I use. If you want to add a transparency to any of the colors, add a leading hex value (#XXcccccc). (XX == "alpha of color")

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#70c656" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#70c656"
                android:endColor="#53933f"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>
Austro answered 6/2, 2013 at 17:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.