Android中drawable分为Bitmap FileNine-Patch FileLayer ListState ListLevel ListTransition DrawableInset DrawableClip DrawableScale DrawableShape Drawable等10余种类型,其中最常用的当属Bitmap File和Nine-Patch File,这两种也是我目前比较熟悉也比较简单的类型,这里暂不单独列举。下面将从Layer List开始,一种一种类型去采用实例的方式进行深度分析。

Layer List

 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.

简单来说,Layer List就是一个由其他的drawable组成的一个列表,按照FIFO进行绘制。

Layer List的XML文件应保存在res/drawable/filename.xml

XML属性描述如下:

XML Attributes
Attribute Name Related Method Description
android:bottom   Bottom coordinate of the layer. 
android:drawable   Drawable used to render the layer. 
android:id   Identifier of the layer. 
android:left   Left coordinate of the layer. 
android:right   Right coordinate of the layer. 
android:top   Top coordinate of the layer. 

 

语法:

<?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"/>

  <item .../>
</layer-list>

 

 

 默认情况下,所有的item中的drawable都会自动根据它附上view的大小而进行缩放,如果你不想图片被缩放,那可以在item中间夹一个<bitmap />,再附上gravity属性,如下:

<item>
 
<bitmapandroid:src="@drawable/image"
         
android:gravity="center"/>
</item>

下面放一个实例:

   xml:res/drawable/layerlist.xml

  

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

    <item
        android:drawable="@drawable/ic_launcher"
        android:left="40dp"
        android:top="40dp">
    </item>
    <item>
        <bitmap
            android:gravity="left"
            android:src="@drawable/ic_launcher" />
    </item>

</layer-list>

 

  layout/activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroud="@drawable/layerlist"
        android:text="@string/hello_world" />

</RelativeLayout>

结果如图:

从上面可以看到,两个图片中,有一个被放大了(正常的item),有一个保持了原图大小(内嵌bitmap的item)。