selector標(biāo)簽房官,可以添加一個或多個item子標(biāo)簽帚呼,而相應(yīng)的狀態(tài)是在item標(biāo)簽中定義的只磷。定義的xml文件可以作為兩種資源使用:drawable和color庆杜。作為drawable資源使用時简软,一般和shape一樣放于drawable目錄下蛮拔,item必須指定android:drawable屬性;作為color資源使用時痹升,則放于color目錄下建炫,item必須指定android:color屬性。
selector狀態(tài):
- android:state_enabled: 設(shè)置觸摸或點(diǎn)擊事件是否可用狀態(tài)疼蛾,一般只在false時設(shè)置該屬性肛跌,表示不可用狀態(tài)
- android:state_pressed: 設(shè)置是否按壓狀態(tài),一般在true時設(shè)置該屬性察郁,表示已按壓狀態(tài)衍慎,默認(rèn)為false
- android:state_selected: 設(shè)置是否選中狀態(tài),true表示已選中皮钠,false表示未選中
- android:state_checked: 設(shè)置是否勾選狀態(tài)稳捆,主要用于CheckBox和RadioButton,true表示已被勾選鳞芙,false表示未被勾選
- android:state_checkable: 設(shè)置勾選是否可用狀態(tài)眷柔,類似state_enabled,只是state_enabled會影響觸摸或點(diǎn)擊事件原朝,而state_checkable影響勾選事件
- android:state_focused: 設(shè)置是否獲得焦點(diǎn)狀態(tài)驯嘱,true表示獲得焦點(diǎn),默認(rèn)為false喳坠,表示未獲得焦點(diǎn)
- android:state_window_focused: 設(shè)置當(dāng)前窗口是否獲得焦點(diǎn)狀態(tài)鞠评,true表示獲得焦點(diǎn),false表示未獲得焦點(diǎn)壕鹉,例如拉下通知欄或彈出對話框時剃幌,當(dāng)前界面就會失去焦點(diǎn);另外晾浴,ListView的ListItem獲得焦點(diǎn)時也會觸發(fā)true狀態(tài)负乡,可以理解為當(dāng)前窗口就是ListItem本身
- android:state_activated: 設(shè)置是否被激活狀態(tài),true表示被激活脊凰,false表示未激活抖棘,API Level 11及以上才支持,可通過代碼調(diào)用控件的setActivated(boolean)方法設(shè)置是否激活該控件
- android:state_hovered: 設(shè)置是否鼠標(biāo)在上面滑動的狀態(tài),true表示鼠標(biāo)在上面滑動最岗,默認(rèn)為false,API Level 14及以上才支持
對圖標(biāo)被點(diǎn)擊切換另一個圖片的:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Non focused states -->
<item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@mipmap/icon_home" />
<item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@mipmap/icon_home_press" />
<!-- Focused states -->
<item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@mipmap/icon_home_press" />
<item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@mipmap/icon_home_press" />
<!-- Pressed -->
<item android:state_selected="true" android:state_pressed="true" android:drawable="@mipmap/icon_home_press" />
<item android:state_pressed="true" android:drawable="@mipmap/icon_home_press" />
</selector>
字體顏色切換:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="#eb4f38" />
<item android:state_active="true" android:color="#eb4f38"/>
<item android:state_selected="false" android:color="#a9b7b7" />
<item android:state_active="false" android:color="#a9b7b7"/>
</selector>
注:item是從上往下匹配的朝捆,如果匹配到一個item那它就將采用這個item般渡,而不是采用最佳匹配的規(guī)則;所以設(shè)置默認(rèn)的狀態(tài)芙盘,一定要寫在最后驯用,如果寫在前面,則后面所有的item都不會起作用了何陆。