Saturday, August 22, 2015

How to create a custom ToggleButton in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#d1d4d4"
    >
    <!-- Default styled ToggleButton -->
    <ToggleButton
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <!-- Custom styled ToggleButton -->
    <ToggleButton
        android:id="@+id/toggle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/toggle_selector"
        android:layout_below="@id/toggle"
        />
</RelativeLayout>
res/drawable/toggle_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/toggle_state_on"
        android:state_checked="true"
        />
    <item
        android:drawable="@drawable/toggle_state_off"
        android:state_checked="false"
        />
</selector>
res/drawable/toggle_state_on.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <!-- Draw a 5dp width border around shape -->
            <stroke
                android:color="#4c975d"
                android:width="5dp"
                />
        </shape>
    </item>
    <!-- Overlap the left, top and right border using background color  -->
    <item
        android:bottom="5dp"
        >
        <shape android:shape="rectangle">
            <solid android:color="#6dd988"/>
        </shape>
    </item>
</layer-list>
res/drawable/toggle_state_off.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <!-- Draw a 5dp width border around shape -->
            <stroke
                android:color="#b1113e"
                android:width="5dp"
                />
        </shape>
    </item>
    <!-- Overlap the left, top and right border using background color  -->
    <item
        android:bottom="5dp"
        >
        <shape android:shape="rectangle">
            <solid android:color="#f51354"/>
        </shape>
    </item>
</layer-list>
More android examples