Android开关 - 打开/关闭开关背景

时间:2015-03-11 07:52:51

标签: android xml

有人知道如何在我的应用程序中实现这样的开关吗? enter image description here

或如何在打开/关闭时更改标准开关的背景颜色?

1 个答案:

答案 0 :(得分:27)

以下是您开始使用的示例XML:

<Switch
    android:layout_width="75dp"
    android:layout_height="25dp"
    android:id="@+id/switch1"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:track="@drawable/switch_track_selector"
    android:switchMinWidth="75dp"
    android:thumb="@drawable/switch_thumb_selector" />

switch_track_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/switch_track_on"
        android:state_checked="true"/>

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

</selector>

switch_track_on.xml

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners
        android:radius="15dp" />
    <size
        android:width="75dp"
        android:height="25dp" />
    <solid
        android:color="#3E98F3" />
    <stroke
        android:width="1dp"
        android:color="#000000" />
</shape>

switch_track_off.xml

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners
        android:radius="15dp" />
    <size
        android:width="75dp"
        android:height="25dp" />
    <solid
        android:color="#FFFFFF" />
    <stroke
        android:width="1dp"
        android:color="#000000" />
</shape>

switch_thumb_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:drawable="@drawable/switch_thumb"
        android:state_checked="true"/>

    <item 
        android:drawable="@drawable/switch_thumb"
        android:state_checked="false"/>

</selector>

switch_thumb.xml

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <size
        android:width="25dp"
        android:height="25dp" />

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

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

</shape>