Now you can Subscribe using RSS

Submit your Email


How to create a favorite button in Android. (Using toggle button)

Vishal Shrestha
You might have come across a favorite button in any dictionary app or android's own contacts app. Today we will be learning how to create a favorite button with identical functionality to those apps.
I did this using a toggle button. I used a toggle button as i wanted to use the setChecked() method of toggle button. The favorite feature is usually required for the items in a list, so i will be talking about it in the context of a custom list, however you can still use the same logic to use it anywhere you need. Now let's jump into the process.

First declare you toggle button, and if you want the default ON and OFF text, then just create add the following to your toggle button - 


Now in your getView() method and set a tag to denote not-Favorited state. Then set the setChecked to false and set the onClickListenter to it- 

favt.setTag(, "white"); //Button with this tags are not yet favorited



If you are unfamilier with the setTag() method, read this to find out more about it.

This is the initial state, till now all the items will have buttons representing non-favorited state. Now we need to check for the elements that are already favorited and set the setChecked method to true and set tag to "red". We are setting set checked to true because we have customized the button to be of red color when it is checked. To learn more about customizing a button using selectors, go here.

if(checkFavorite(current))         //This is your custom method
                                                 //if the item already exists in the favorites
favt.setChecked(true);          //To dispaly different icon if already favorited
favt.setTag(, "red");   

Now our displaying is complete, now we need to handle the clicks. If an already favorited button is clicked again we need to un-favorite it and change the icon, and if it's not a favorite we need to make it a favorite and change the icon. We can do it like this-

public void onClick(View view) {
// TODO Auto-generated method stub
ToggleButton favt = (ToggleButton) view.findViewById(;
String color = (String) view.getTag(; //Red = Favorited
RowData fav = (RowData) getItem(pos);
favt.setTag(, "red");
favt.setTag(, "white");

If you have any doubts please feel free to comment below or contact me.

Vishal Shrestha / Author & Editor

A developer by profession, an adventurer by heart, writing riveting poems and poetic code. You can find me having a few rounds with the heavy bag to let out the steam ;)


Post a Comment

Coprights @ 2017 | The Code City by Vishal Shrestha Vishal Shrestha