做應用時,可能會需要動态改變控件的背景圖檔,如果僅僅是簡單的點選,選中之類的事件,如果靠程式中寫監聽的代碼就顯得太麻煩了,在這種情況下,你可以使用selector動态改變控件背景拉:)
1。在res/drawable目錄下建一個mybutton.xml檔案,根據需要,不同的狀态下建立不同的item,并對應相應的圖檔
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false"
android:drawable="@color/transparent" />
<!-- Even though these two point to the same resource, have two states so the drawable will invalidate itself when coming out of pressed state. 注意這句話-->
<item android:state_focused="true" android:state_enabled="false"
android:state_pressed="true"
android:drawable="@drawable/selector_background_disabled" />
android:drawable="@drawable/lselector_background_disabled" />
<item android:state_focused="true" android:state_pressed="true"
android:drawable="@drawable/selector_background_transition" />
<item android:state_focused="false" android:state_pressed="true"
<item android:state_focused="true"
android:drawable="@drawable/selector_background_focus" />
</selector>
2。在構造layout是引用這個xml
<ImageButton
android:id="@+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/mybutton">
</ImageButton>