好多人都埋怨Android控件没有iOS高大上,而且不好用,今天闲着没事,就花点时间,写了个Switch,希望能够帮助需要的小伙伴们。
先看下效果。
虽然没有实现切换的动画,但最起码看上去没有一些接近了,废话不多说,上代码。
鉴于项目中可能会多出用到Switch开关,所以抽出一个style, 方便使用。
在style.xml中添加如下代码:
<style name="MySwitch"> <!--track是switch轨迹部分,这里我们用了一个selector来解决不同状态下轨迹的颜色--> <item name="android:track">@drawable/switch_track</item> <!--thumb是switch滑块,这里我们用了Widget.AppCompat.CompoundButton.Switch下带的资源,如果有需要,请自行更换图标--> <item name="android:thumb">@drawable/abc_switch_thumb_material</item> <item name="android:background">@null</item> <!--switch上的文字,插入占位符,解决部分手机不能显示问题--> <item name="android:textOn"> </item> <item name="android:textOff"> </item> <!--这个东西才能控制整个开关的宽度, 有些人会发现设置width会无效,设置一下这个就好啦--> <item name="android:switchMinWidth">50dp</item> </style>drawable/switch_tradck.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true"> <shape> <solid android:color="#4dd664" /> <corners android:radius="30dp"/> <size android:width="50dp" android:height="26dp" /> </shape> </item> <item android:state_checked="false"> <shape> <solid android:color="#ffffff" /> <corners android:radius="30dp"/> <!--低版本手机需要设置size才能正常显示track--> <size android:width="50dp" android:height="28dp" /> <!--设置边框--> <stroke android:color="#e4e4e4" android:width="1dp" android:dashGap="0dp" android:dashWidth="0dp"/> </shape> </item> </selector> 这样整个style就基本完成了,用起来也非常简单. <Switch android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/MySwitch"/> 齐活, 就是这么简单, 有什么问题也随时联系,刚开始写博文,不怎么会弄,见谅~~~