Android自定义转换开关按钮的样式实例详解

  

 Android自定义转换开关按钮的样式实例详解

  

封面   

GitHub传送门

  

  

本文主要讲的是在Android原生控开关件的基础上进行样式自定义,内容很简单,但是在实现的过程中还是遇到了一些问题,在此记录下来,希望对大家能够有所帮助,看下效果图:

  

 Android自定义转换开关按钮的样式实例详解

  

自定义样式

  

  

<强> 2.1原生样式

  

首先看下原生的效果(Android 7.1):

  

 Android自定义转换开关按钮的样式实例详解

  

原生效果

  

布局文件如下:

        & lt;开关   android: layout_width=" wrap_content "   android: layout_height=" wrap_content "/祝辞      

<强> 2.2自定义样式

  

设计给的效果图大多数都不会使用原生效果,所以我们需要对样式进行自定义,比如下面这种效果:

  

 Android自定义转换开关按钮的样式实例详解

  

自定义效果

  

<强>定义开关的开关按钮状态:

  

开启状态:switch_custom_thumb_on.xml

        & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比;   & lt;形状xmlns: android=" http://schemas.android.com/apk/res/android "   android:形状=巴衷病北?   & lt;固体android:颜色=" # 94 c5ff "/比;   大小& lt;   android:宽度=" 20 dp”   android:身高=" 20 dp/比;   & lt;/shape>      

关闭状态:switch_custom_thumb_off.xml

        & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比;   & lt;形状xmlns: android=" http://schemas.android.com/apk/res/android "   android:形状=巴衷病北?   & lt;固体android:颜色=" # AAA”/比;   大小& lt;   android:宽度=" 20 dp”   android:身高=" 20 dp/比;   & lt;/shape>      

定义一个选择器:switch_custom_thumb_selector.xml

        & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比;   & lt;选择xmlns: android=" http://schemas.android.com/apk/res/android "比;   & lt;项目android:可拉的=" @drawable/switch_custom_thumb_on”android: state_checked=" true "/比;   & lt;项目android:可拉的=" @drawable/switch_custom_thumb_off”android: state_checked=癴alse”/祝辞   & lt;/selector>      

到此开关的开关按钮状态就定义好了,接下来定义一下开关滑动轨道的状态:

  

开启状态:switch_custom_track_on.xml

        & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比;   & lt;形状xmlns: android=" http://schemas.android.com/apk/res/android "   android:形状=熬匦巍北?   & lt;固体android:颜色=" # B6D6FE”/比;   & lt;中风   android:宽度=" 5 dp "   android:颜色=" # 00000000 "/比;   & lt;角落android:=" 20 dp/半径比;   & lt;/shape>      

关闭状态:switch_custom_track_off.xml

        & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比;   & lt;形状xmlns: android=" http://schemas.android.com/apk/res/android "   android:形状=熬匦巍北?   & lt;固体android:颜色=" # E3E3E3”/比;   & lt;中风   android:宽度=" 5 dp "   android:颜色=" # 00000000 "/比;   & lt;角落android:=" 20 dp/半径比;   & lt;/shape>      

定义一个选择器:switch_custom_track_selector.xml

        & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比;   & lt;选择xmlns: android=" http://schemas.android.com/apk/res/android "比;   & lt;项目android:可拉的=" @drawable/switch_custom_track_on”android: state_checked=" true "/比;   & lt;项目android:可拉的=" @drawable/switch_custom_track_off”android: state_checked=癴alse”/祝辞   & lt;/selector>      

开关自定义样式,默认情况下开关按钮和滑动轨道的高度是一样的,并且在xml文件中对轨道的宽高设置是无效的,如果想要修改轨道的高度可以这样做:

  

Android自定义转换开关按钮的样式实例详解