How to Set Opacity (Alpha) for View in Android
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.
Solution 1:
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).
Solution 2:
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)