ColorStateList資源

Demo

MainActivity.java

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
   }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:id="@+id/btn"
        android:layout_centerInParent="true"
        android:textSize="16sp"
        android:background="#07B226"
        android:textColor="@color/textcolor"
        android:text="點擊" />
</RelativeLayout>

textcolor.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:color="#164869"
        android:state_pressed="true"></item>
    <item android:color="#ffffff"
        android:state_pressed="false"></item>
</selector>

運行

這裏寫圖片描述

ColorStateList資源

資源路徑

res/color/filename.xml

資源的使用

在代碼中使用: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: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>元素。

<item>
    定義特定狀態的color,必須是的子元素。

android:color 屬性值爲16進制顏色。
- #RGB
- #ARGB
- #RRGGBB
- #AARRGGBB

android:state_pressed
屬性值爲Boolean類型。“true”表示按下狀態使用(例如按鈕按下);“false”表示非按下狀態使用。

android:state_focused
屬性值爲Boolean類型。“true”表示聚焦狀態使用;“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欄拉下或對話框顯示)。

注意事項

ColorStateList中第一個匹配當前狀態的item會被使用。因此,如果第一個item沒有任何狀態特性的話,那麼它將每次都被使用,這也是爲什麼默認的值必須總是在最後。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章