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 會套用顏色清單至檢視畫面:
<Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/button_text" android:textColor="@color/button_text" />
- 另請參閱: