Android Switch开关,高仿iOS自定义样式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39249422/article/details/90478639

首先我们先写一个样式

drawable/switch_style.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="#fff"/>  
                <corners android:radius="30dp"/>  
                <size android:width="50dp" android:height="20dp"/>  
            </shape>  
        </item>  
        <item android:state_checked="false">  
            <shape>  
            <solid android:color="#ffffff" />  
            <corners android:radius="30dp"/>  
            <!--低版本手机需要设置size才能正常显示track-->  
            <size android:width="50dp" android:height="20dp" />  
            <!--设置边框-->  
            <stroke android:color="#e4e4e4" android:width="1dp" android:dashGap="0dp" android:dashWidth="0dp"/>  
        </shape>  
        </item>  

</selector>

然后在style.xml中添加如下代码:

<style name="Switch">  
       <!--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">40dp</item>  
 </style>

最后再布局文件里面添加空间

<Switch
    android:id="@+id/switch_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/Switch"/>

这样整个控件就基本完成了,用起来也非常简单.

mSwitchBtn.setOnCheckedChangeListener((buttonView, isChecked) -> {
    if (isChecked){
        SwitchBtn = "1";
        mLl6.setVisibility(View.GONE);
        ToastUtils.showToast("开");
    }else {
        SwitchBtn = "0";
        mLl6.setVisibility(View.VISIBLE);
        ToastUtils.showToast("关");
    }
});

猜你喜欢

转载自blog.csdn.net/qq_39249422/article/details/90478639