1. 程式人生 > >Android 自定義 Switch

Android 自定義 Switch

效果

實現方法

1、drawable下建立滑動圓點  switch_thumb

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">
    <size
        android:width="30dp"
        android:height="30dp">
    </size>
    <solid
        android:color="@android:color/white">
    </solid>

</shape>

2、drawable下建立選中樣式   switch_track_on

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">

    <solid
        android:color="@color/businesstop">
    </solid>

    <corners
        android:radius="30dp">
    </corners>

</shape>

3、drawable下建立非選中樣式    switch_track_off

<?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">
    </solid>
    <corners
        android:radius="30dp">
    </corners>
</shape>

 

4、drawable下建立switch樣式   switch_track

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_checked="true"
        android:drawable="@drawable/switch_track_on"></item>
    <item
        android:state_checked="false"
        android:drawable="@drawable/switch_track_off"></item>
</selector>

5、layout.xml下switch引用自定義滑動點和樣式即可

<Switch
    android:id="@+id/ycsw"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_track"
    android:gravity="center"/>