Android仿微信开关按钮SwitchButton

使用系统自带的功能,只需要设置selector选择器就可实现下面的功能
Android仿微信开关按钮SwitchButton
Android仿微信开关按钮SwitchButton

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

xml设置

Android仿微信开关按钮SwitchButton

这里需要注意的地方: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>

Android仿微信开关按钮SwitchButton

滑动背景: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>

Android仿微信开关按钮SwitchButton

Android仿微信开关按钮SwitchButton

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中的一个简单的应用。