Android:自定义switch控件,设置开关的颜色、属性等

Java 发表评论
<Switch
    android:id="@+id/togBtn_OCROpen"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:checked="true"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dip"
    android:textOn="     "
    android:textOff="     "
    android:textSize="16dp"
    android:thumb="@drawable/thumb"
    android:track="@drawable/switch_track"
    ></Switch>
在res/drawable/下新建switch_track.xml文件:

<?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>

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

    <solid
        android:color="#006487">
    </solid>

    <corners
        android:radius="20sp">
    </corners>

    <size
        android:width="50dp"
        />
    <stroke android:color="#00000000" android:width="10dp"/>
</shape>
switch_track_off.xml:

<?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="20sp">
    </corners>
    <stroke android:color="#00000000" android:width="10dp"/>

    <size
        android:width="50dp"
        />
</shape>
新建res/drawable/thumb.xml:

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

    <!-- 高度40 -->
<size android:height="20sp" android:width="20sp"/>
<!-- 圆角弧度 20 -->
<corners android:radius="18sp"/>

<!-- 变化率 -->
<gradient
    android:endColor="#f1f5f8"
    android:startColor="#f1f5f8" />

<stroke android:width="1dp"
    android:color="#006487"/>

</shape>

发表评论

邮箱地址不会被公开。 必填项已用*标注

昵称 *