ColorStateList
是可以在 XML 中定義及套用為顏色的物件,會視其套用的 View
物件狀態實際變更顏色。舉例來說,Button
小工具可置於多種狀態的其中一種:已按下、已聚焦或兩者皆非。您可以使用顏色狀態清單為每個狀態提供不同顏色。
您可以在 XML 檔案中說明狀態清單。每個顏色都會在單一 <selector>
元素內的 <item>
元素中定義。每個 <item>
都會使用多種不同的屬性,說明要在何種狀態下使用。
每次狀態變更時,狀態清單都會從頂部到底部進行測定,而且會使用符合目前狀態的第一個項目;此選擇並「不是」根據「最符合」的條件決定,而單純是依據滿足狀態最低條件需求的第一個項目。
注意:如要提供靜態顏色資源,請直接使用顏色值。
- 檔案位置:
res/color/filename.xml
系統會把檔案名稱當做資源 ID。- 所編譯資源資料類型:
ColorStateList
的資源指標。- 資源參照:
-
Java:
R.color.filename
XML:@[package:]color/filename
- 語法:
-
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:color="hex_color" android:lStar="floating_point_value" android:state_pressed=["true" | "false"] android:state_focused=["true" | "false"] android:state_selected=["true" | "false"] android:state_checkable=["true" | "false"] android:state_checked=["true" | "false"] android:state_enabled=["true" | "false"] android:state_window_focused=["true" | "false"] /> </selector>
- 元素:
- 例如:
- 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>
以下版面配置 XML 會將顏色清單套用至
View
:<Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/button_text" android:textColor="@color/button_text" />
- 另請參閱: