Is there a way to set drawable's Alpha using XML?

Easy like itself . I wanna make an alpha button , which would have a selected drawable this way:

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

    <!-- Play/Pause -->
    <item android:state_selected="false" android:drawable="@drawable/item" />
    <item android:state_selected="true" android:drawable="@drawable/item" />

</selector>

I would wanna make something like this:

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

    <!-- Play/Pause -->
    <item android:alpha="125" android:state_selected="false" android:drawable="@drawable/item" />
    <item android:alpha="255" android:state_selected="true" android:drawable="@drawable/item" />

</selector>

Thanks for all .


It's been a while since the OP, but personally found a solution that worked a lot better for me than the suggested answers. Creating a BitmapDrawable makes is easily possible to set the alpha:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/your_drawble"
    android:alpha="77">
</bitmap>

Alpha can be any value between 0 and 255. Note that it is sort of the inverse of the HEX color value alpha, as for example 70% alpha would be B3 in HEX and 77 in the BitmapDrawable.


I achieved the same using a drawable

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="#5000ddff" />
</shape>

Over here used the alpha 50, which sets the opacity level. Hope that helps


I have been looking for the same thing. Even though this is posted over four years ago, this is the top post when googling the issue, so I'll reply here.

This is my solution

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <bitmap android:alpha="@integer/not_pressed_alpha" android:src="@drawable/item"/>
    </item>
    <item android:state_pressed="true" android:drawable="@drawable/item" />
</selector>

For those who have the same problem as OP, AppCompat now allows you to set 'alpha' parameter, as he wished in his target code:

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

    <!-- Play/Pause -->
    <item android:alpha="125" android:state_selected="false" android:drawable="@drawable/item" />
    <item android:alpha="255" android:state_selected="true" android:drawable="@drawable/item" />

</selector>

More info here.