A LayerDrawable
is a drawable object that manages an array of other drawables. Each drawable in the list is drawn in the order of the list—the last drawable in the list is drawn on top.
Each drawable is represented by an <item>
element inside a single <layer-list>
element.
res/drawable/filename.xml
The filename is used as the resource ID.
LayerDrawable
.
R.drawable.filename
In XML:
@[package:]drawable/filename
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:drawable="@[package:]drawable/drawable_resource" android:id="@[+][package:]id/resource_name" android:top="dimension" android:right="dimension" android:bottom="dimension" android:left="dimension" /> </layer-list>
<layer-list>
<item>
elements.
attributes:
xmlns:android
"http://schemas.android.com/apk/res/android"
.
<item>
<selector>
element. Accepts child
<bitmap>
elements.
attributes:
android:drawable
android:id
"@+id/name"
. The plus symbol indicates that this should be created as a new ID. You can use this identifier to retrieve and modify the drawable with
View.findViewById()
or
Activity.findViewById()
.
android:top
android:right
android:bottom
android:left
All drawable items are scaled to fit the size of the containing View, by default. Thus, placing your images in a layer list at different positions might increase the size of the View and some images scale as appropriate. To avoid scaling items in the list, use a <bitmap>
element inside the <item>
element to specify the drawable and define the gravity to something that does not scale, such as "center"
. For example, the following <item>
defines an item that scales to fit its container View:
<itemandroid:drawable="@drawable/image"/>
To avoid scaling, the following example uses a <bitmap>
element with centered gravity:
<item><bitmapandroid:src="@drawable/image"android:gravity="center"/></item>
res/drawable/layers.xml
:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <bitmap android:src="@drawable/android_red" android:gravity="center" /> </item> <item android:top="10dp" android:left="10dp"> <bitmap android:src="@drawable/android_green" android:gravity="center" /> </item> <item android:top="20dp" android:left="20dp"> <bitmap android:src="@drawable/android_blue" android:gravity="center" /> </item> </layer-list>
Notice that this example uses a nested <bitmap>
element to define the drawable resource for each item with a "center" gravity. This ensures that none of the images are scaled to fit the size of the container, due to resizing caused by the offset images.
This layout XML applies the drawable to a View:
<ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/layers" />
The result is a stack of increasingly offset images: