仿微信Switch样式

2020-03-20  本文已影响0人  编程的猫

先上效果:


image.png
image.png

直接上代码:

<?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>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#7ED53D" />
    <corners android:radius="20dp" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/darker_gray" />
    <corners android:radius="20dp" />
</shape>

在activity中使用:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".wheel.RvActivity">

  <Switch
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:checked="false"
      android:padding="8dp"
      android:text="开启WIFI"
      android:textColor="@android:color/black"
      android:layout_marginTop="80dp"
      android:layout_centerInParent="true"
      android:id="@+id/sw_auto_button"
      android:thumb="@drawable/switch_ios_thumb"
      android:track="@drawable/switch_ios_track_selector"/>

</RelativeLayout>
 Switch swAutoPlay = findViewById(R.id.sw_auto_button);

        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);
                }
            }
        });

上一篇下一篇

猜你喜欢

热点阅读