ColorStateList對象可以在XML中定義,像color一樣使用,它能根據它應用到的View對象的狀態實時改變顏色。例如,Button可以存在多種狀態(pressed、focused或other),如果使用ColorStateList,你就能為它的每個狀態提供不同的顏色。
你可以在XML文件中描述狀態列表。每種顏色定義在一個<item>元素里,<item>放在單個<selector>元素里。每個<item>使用不同的特性來描述在何種狀態下使用。
當每次狀態改變時,StateList都會從上到下遍歷一次,第一個匹配當前狀態的item將被使用——選擇的過程不是基於“最佳匹配”,只是符合state的最低標准的第一個item。
注意:如果你想提供一個靜態的color資源,使用簡單的Color值。
File Location:res/color/filename.xml(文件名將作為資源ID)
Compiled Resource Datatype:指向ColorStateList的資源指針
Resouce Reference:R.color.filename(Java)、@[package:]color/filename(XML)
Syntax:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="hex_color"
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>
Elements:
<selector>
必須。必須是根元素。包含一個或多個<item>元素。
Attributes:
xmlns:android
String,必須。定義XML的命名空間,必須是
“http://schemas.android.com/apk/res/android”.
<item>
定義特定狀態的color,通過它的特性指定。必須是<selector>的子元素。
Attributes:
android:color
16進制顏色。必須。這個顏色由RGB值指定,可帶Alpha。
這個值必須以“#”開頭,后面跟隨Alpha-Red-Green-Blue信息:
l #RGB
l #ARGB
l #RRGGBB
l #AARRGGBB
android:state_pressed
Boolean。“true”表示按下狀態使用(例如按鈕按下);“false”表示非按下狀態使用。
android:state_focused
Boolean。“true”表示聚焦狀態使用(例如使用滾動球/D-pad聚焦Button);“false”表示非聚焦狀態使用。
android:state_selected
Boolean。“true”表示選中狀態使用(例如Tab打開);“false”表示非選中狀態使用。
android:state_checkable
Boolean。“true”表示可勾選狀態時使用;“false”表示非可勾選狀態使用。(只對能切換可勾選—非可勾選的構件有用。)
android:state_checked
Boolean。“true”表示勾選狀態使用;“false”表示非勾選狀態使用。
android:state_enabled
Boolean。“true”表示可用狀態使用(能接收觸摸/點擊事件);“false”表示不可用狀態使用。
android:window_focused
Boolean。“true”表示應用程序窗口有焦點時使用(應用程序在前台);“false”表示無焦點時使用(例如Notification欄拉下或對話框顯示)。
注意:記住一點,StateList中第一個匹配當前狀態的item會被使用。因此,如果第一個item沒有任何狀態特性的話,那么它將每次都被使用,這也是為什么默認的值必須總是在最后(如下面的例子所示)。
Examples:
XML文件保存在res/color/button_text.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#ffff0000"/> <!-- pressed -->
<item android:state_focused="true"
android:color="#ff0000ff"/> <!-- focused -->
<item android:color="#ff000000"/> <!-- default -->
</selector>
這個Layout XML會應用ColorStateList到一個View上:
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:textColor="@color/button_text" />