Android Custom Toggle Button Example (iOS like toggle buttons)

Toggle buttons are a great way of getting user input when we need only either yes or no from user. Technically speaking, when we need user input in boolean form- toggle buttons can come handy.

Adding a toggle button to your view and getting its status is very easy, you can have a look what Google has to say about them here.

But, toggle buttons provided with sdk are slightly dull and you just can’t go around and use them everywhere. Well, you can use different images for toggle button states. You can define a button for its checked state and other button for unchecked state. With this you can get a switch-look also.

Lets look how you can get a custom toggle button in your application. The images we are using for different states are inspired from toggle button of iOS, I found them classy (lets have a bit open mind here 😉 ).

In action:

Custom toggle button android

Full source code at github.

 Put toggle_off.png and toggle_on.png in drawable folder. You can replace them with your own images.

toggle_on
toggle_off

Create toggle_selector.xml in drawable. Define drawables for different states.

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_on"
android:state_checked="true"/>

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

Define ToggleButton in activity_main.xml


<ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/toggle_selector"
        android:checked="false"
        android:text=""
        android:textOff=""
        android:textOn="" />

Important: We have to set background of our toggle button to toggle_selector defined in drawable folder. It will set the image according to its state. Also, to get desired effect as shown in demo above – we must set android:textOff and android:textOn to empty string otherwise text will appear on top of our images.

To get the status from ToggleButton, we can set a onCheckedChangeListener on our ToggleButton as shown below.

toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
				text.setText("Status: " + isChecked);
			}
		});

We are updating text of TextView when toggleButton is tapped. Checkout full source code on github.

7 thoughts on “Android Custom Toggle Button Example (iOS like toggle buttons)

Leave a comment