Kelib
Kelib

Reputation: 648

XML drawable composed of png and overlay

I have a png button, which is enabled, non-pressed. When user click the button, I want only to darken the png. I need something like this:

  <selector xmlns:android="http://schemas.android.com/apk/res/android" >
  //normal button with background my_button.png
        <item 
            android:state_enabled="true" 
            android:drawable="@drawable/my_button"   //my_button.png
            />
  //pressed button with background my_button.png overlayed by 50% black
        <item 
            android:state_pressed="true"
            android:state_enabled="true"    
            >
            <RelativeLayout 
               android:layout_width="wrap_content"
               android:layout_height="wrap_content">

              <bitmap  android:src="@drawable/my_button"/>
              <color android:color="#00000088"/>
            </RelativeLayout>
        </item>      
    </selector>

Is there some way how to do that? Or do I must have another png file?

Upvotes: 10

Views: 5959

Answers (3)

timemanx
timemanx

Reputation: 4523

This should work

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_enabled="true"
        android:drawable="@drawable/my_button" />
    <item>
        <selector>
            <item
                android:state_pressed="true"
                android:state_enabled="true">
                <color android:color="#00000088" />
            </item>
        </selector>
    </item>

</layer-list>

Upvotes: 3

swbandit
swbandit

Reputation: 2006

The order of the items in the selector XML make a difference. The first match is what is going to get displayed. As you see in marmor's answer, the normal state of the button is listed at the end.

Another thing to keep in mind is that if you are using 9-patch images (.9.png), the color will only be applied to the content area. So if you want the color to be overlayed over the whole image, make sure to mark the whole image as the content area.

Upvotes: 0

marmor
marmor

Reputation: 28179

In my_button_bg.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/button_normal"/>
</selector>

button_normal is a png

button_pressed is an xml:

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

where btn_bg_pressed_mask is a color:

<color name="btn_bg_pressed_mask">#19000000</color>

Upvotes: 11

Related Questions