Android Custom Toggle Button

Android Custom Toggle Button

We previously customized progress bar with Android Custom Progress Bar Using XML Drawables tutorial. This time we will go with custom toggle button in android.

1. Toggle button Introduction

Toggle buttons are handy when you want to allow your users to switch between two states. When it comes to two states OR on/off OR selection, there are several things like you can use CheckBox, Switch, Toggle Button, Radio Button. But It’s probably up to the case where they are used.

 

2. What user experience has to say about toggle button?

  1. Toggle Button with effective customization shows current state much more visible. Using Toggle Button is makes more sense when there are number of buttons to select states between (not talking regarding single selection RadioButtons).
  2. CheckBoxes makes more sense for showing things which can be shown separately.
  3. While using Toggle Button it should be taken care that they show their activation states in a way user can understand easily.

 

3. Class & Api Availability

Toggle Button is direct subclass of CompoundButton and is available since API level 1.

Now let us dirty our hands. We are going to create 7 custom toggle buttons that shows weekdays like in alarm application to select days of week on which your alarms should ring.

 

4. Create a new android studio project with empty activity.

After creating project I have my launcher activity in manifest with name MainActivity and its layout file as activity_main.xml

 

5. Create drawable for custom toggle button’s on/activated state. (toggle_activated.xml)

 

6. Create drawable for custom toggle button’s off/deactivated state. (toggle_deactivated.xml)

 

7. Further make one more drawable to be able to combine on and off state of custom toggle button. (toggle_drawable.xml)

 

8.  Now we can make a style for our custom toggle button inside styles.xml.

 

9. And we are ready to design layout to show custom toggle buttons. (activity_main.xml)

 

10. Paste below code inside MainActivity.java.

 

Of course, instead of plain colors you can replace drawables with your custom images as well inside toggle_activated.xml and toggle_deactivated.xml.

Here is the that will be shown on your screen.

custom toggle button
custom toggle button

Leave a Reply

Your email address will not be published. Required fields are marked *