Ben Ezard Ben Ezard - 5 days ago 5
Android Question

Android Overlay Image On Top Of Background Image Using XML Selector

Basically what the title says:

I have a View that I have set the background image for (via the android:background attribute in XML), and I'd like to overlay another image when the user presses on the view

I know that you can use XML selectors to CHANGE the background image when the view is pressed, but is it possible to overlay an image instead?

Or will I just have to have 2 images - the plain one and then the one with the overlay added?


Thanks in advance :)

Answer

Thanks to Chaosit, I came up with this solution:
In res/xml you create a selector file, e.g. selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/image_with_overlay" android:state_pressed="true" />
    <item android:drawable="@drawable/image" />
</selector>

In res/drawable, you then create a layer-list, e.g. image_with_overlay.xml

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

Then in the View that you want to have this property, you simply use android:background="@xml/selector"

Then you're all done :-)

Comments