自定义ToggleButton的样式

1.案例效果图

clip_image001 clip_image002

选中 未选中

2.准备相关的资源

2.1准备图片(一般放在drawable-hdpi目录下)

clip_image003

clip_image004 clip_image005

toggle_btn_checked.png toggle_btn_unchecked.png

2.2准备透明的颜色

clip_image006

<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目录下才能完全显示图片(高分辨率下)

原文地址:https://www.cnblogs.com/lxcao/p/4297914.html