Android – Custom toggle button example

By -
Problem: How to customize toggle button with custom images in android?
Solution:

Step 1: Create 2 images for ON and OFF state of toggle button, place these 2 images inside the Drawable folder. FYI, i have used 9-patch tool to create images for the states.

Step 2: Now, create a selector file for your toggle button, which is used to get state of button and define drawable accordingly.

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

    <item android:drawable="@drawable/bg_fbautoshare_selected" android:state_checked="true" android:state_pressed="true"/>
    <item android:drawable="@drawable/bg_fbautoshare_selected" android:state_checked="true" android:state_focused="false"/>
    <item android:drawable="@drawable/bg_fbautoshare_normal" android:state_checked="false" android:state_pressed="true"/>
    <item android:drawable="@drawable/bg_fbautoshare_normal" android:state_checked="false" android:state_focused="false"/>

</selector>

Step 3: Now, create a XML layout and place ToggleButton on the layout file.

Step 4: Define the android:background attribute of ToggleButton with the selector file created above.

Step 5: Also define the android:textOff and android:textOn attributes of a ToggleButton inside the XML layout file.

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="10dp" >

    <ToggleButton
        android:id="@+id/toggleFBAutoShare"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/btntoggle_selector"
        android:textColor="@android:color/white"
        android:textOff="TechnoTalkative OFF"
        android:textOn="TechnoTalkative ON" />

</LinearLayout>

Download example code from here: Android Custom ToggleButton example

CEO & Co-Founder at SolGuruz® | Organiser @ GDG Ahmedabad | Top 0.1% over StackOverflow | 15+ years experienced Tech Consultant | Helping startups with Custom Software Development

Loading Facebook Comments ...
Loading Disqus Comments ...