Android仿微信开关按钮SwitchButton

版权声明:本文为徐代龙原创文章,未经徐代龙允许不得转载。网络资源网站:xudailong.cc 福利网站:www.00reso.com 公众号:蛇崽网盘教程资源 https://blog.csdn.net/xudailong_blog/article/details/86134544

使用系统自带的功能,只需要设置selector选择器就可实现下面的功能
在这里插入图片描述
在这里插入图片描述

这里说明一下:使用Android原生的switch选择器难免在某些布局上显得很丑。UI一般给图都会给出上诉的图

xml设置

在这里插入图片描述

这里需要注意的地方:Switch下的thumb与track,一个是滑块,一个是滑动背景。

Selector

滑块:switch_ios_thumb.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#FFF" />
    <stroke
        android:width="3dp"
        android:color="#00000000" />
    <size
        android:width="20dp"
        android:height="20dp" />
</shape>

在这里插入图片描述

滑动背景:switch_ios_track_selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/switch_ios_track_on" android:state_checked="true" />
    <item android:drawable="@drawable/switch_ios_track_off" android:state_checked="false" />
</selector>

在这里插入图片描述

在这里插入图片描述

Activity中调用
        swAutoPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SPUtils.getInstance().put(Constants.AUTO_PALY_IN_WIFI, isChecked);
                if (isChecked) {
                    Log.e(TAG, "onCheckedChanged: 开启" + isChecked);
                } else {
                    Log.e(TAG, "onCheckedChanged: 关闭" + isChecked);
                }
            }
        });

以上就是SwitchButton中的一个简单的应用。

猜你喜欢

转载自blog.csdn.net/xudailong_blog/article/details/86134544