1.案例效果圖
選中 未選中
2.准備相關的資源
2.1准備圖片(一般放在drawable-hdpi目錄下)
toggle_btn_checked.png toggle_btn_unchecked.png
2.2准備透明的顏色
<color name="transparent">#00000000</color>
3.樣式文件(toggle_button.xml)
3.1樣式文件位置通常在drawable目錄下定義
3.2樣式代碼
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 選中樣式 -->
<item android:drawable="@drawable/toggle_btn_checked" android:state_checked="true"/>
<!-- 未選中樣式 -->
<item android:drawable="@drawable/toggle_btn_unchecked" android:state_checked="false"/>
</selector>
4.應用樣式(main.xml)
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/transparent"
android:button="@drawable/toggle_button"
android:text=""
android:textOff=""
android:textOn="" />
4.1 為了只顯示圖片需要設置text、textOff、textOn屬性的內容為空字符串
4.2 為了充分顯示出圖片,背景設置為透明的顏色 #0000000
4.3 為了顯示圖片按鈕,在button屬性上應用樣式
4.4 控件的寬度和高度屬性設置為"wrap_content",圖片資源最好放在drawable-hdpi目錄下才能完全顯示圖片(高分辨率下)