StateListDrawable是在XML中定義的drawable對象,我們可以通過設置不同item下的圖片來顯示不同狀態,它的XML文件定義如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize=["true" | "false"]
android:dither=["true" | "false"]
android:variablePadding=["true" | "false"] >
<item
android:drawable="@[package:]drawable/drawable_resource"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_active=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
</selector>
<selector>爲根節點,其下子節點只有一個爲item
android:constantSize: boolean型,默認爲false,
android:dither:boolean型,默認爲true,當位圖與屏幕的像素配置不一樣時(例如,一個ARGB爲8888的位圖與RGB爲555的屏幕)會自行遞色(dither)。設置爲false時不可遞色。
android:variablePadding:boolean型,默認爲false,當設置爲true時,則drawable的padding值隨當前選擇的狀態而改變。
<item>通過其屬性定義當選中某種狀態的時候應該顯示的圖片資源;
android:drawable:必須的參數,drawable資源;
android:state_pressed:boolean型,設置爲true時表示當對象被按下時該item會顯示或者說生效,爲false時表示該item爲默認狀態非選中狀態;
android:state_focused:boolean型,爲true時表示該item生效爲焦點在對象上時,false爲非選中狀態;
android:state_selected:boolean型,同上功能,該屬性表示的時被選擇狀態;
android:state_checkable:boolean型,僅僅用在可以選擇widget上,爲true表示可選擇,爲false表示不可選;
android:state_checked:boolean型,爲true時,表示當選中時該item生效,false爲未選中時生效;
android:state_enabled:boolean型,當爲true時,該item在對象可激活時生效,如該對象可以接受觸摸或者點擊事件時;
android:state_window_focused:boolean型,爲true時,表示該item在當前窗口焦點爲該應用程序窗口時生效也就是說該應用程序窗口爲foreground,否則爲false;
當我們要定義一個自己需要的狀態選擇功能的文件時,其實現方式主要可簡括爲兩步:
1. 在/res/drawable 目錄下建立自己需要的.xml文件如button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/button_pressed" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/button_focused" /> <!-- focused -->
<item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>
2. 在layout xml文件中引用:如
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/button" />