Android XML layer-list: How to position the top layer

Asaf Nevo picture Asaf Nevo · Oct 14, 2013 · Viewed 16.2k times · Source

I have this XML drawable - tab_background_unselected:

<?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/background_grey" />            
        </shape>
    </item>

</layer-list>

which creates this shape:

background rectangle

and this arrow shape xml drawable - tab_selected_arrow:

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

    <item>
        <rotate
            android:fromDegrees="45"
            android:pivotX="-40%"
            android:pivotY="87%"
            android:toDegrees="45" >
            <shape android:shape="rectangle" >
                <solid android:color="@color/background_dark_green" />
            </shape>
        </rotate>
    </item>

</layer-list>

which creates this shape:

top layer triangle

I'm using this drawable XML (instead of PNG file) in order to create a layer-list:

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

    <item android:drawable="@drawable/tab_background_unselected">
    </item>
    <item android:drawable="@drawable/tab_selected_arrow">
    </item>

</layer-list>

but I want the final image to look like this:

final image

I don't know how to set the gravity of the arrow (the second item and the top layer) to center|bottom... I've tried using bitmap tag but it only accepts image files.

I need this to be a XML drawable because

  1. I need it to be inside a drawable selector
  2. I don't want to make it a PNG and create different file for each screen resolution

Answer

marmor picture marmor · Nov 25, 2013

Use an inner Bitmap drawable inside the item, and set gravity for it:

<item android:drawable="@drawable/tab_background_unselected">
</item>
<item>
    <bitmap
        android:gravity="bottom|center_horizontal"
        android:src="@drawable/tab_selected_arrow" />
</item>