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 –
android:textOn=""
android:textOff=""
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(R.id.color, “white”); //Button with this tags are not yet favorited
favt.setChecked(false);
favt.setOnClickListener(this);
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
//database
//if the item already exists in the favorites
//database
{
favt.setChecked(true); //To dispaly different icon if already favorited
favt.setTag(R.id.color, “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(R.id.toggleButton1);
String color = (String) view.getTag(R.id.color); //Red = Favorited
RowData fav = (RowData) getItem(pos);
if(color.equals(“white”))
{
addFavorite(fav);
favt.setTag(R.id.color, “red”);
}
else
{
removeFavorite(fav);
favt.setTag(R.id.color, “white”);
}
}
If you have any doubts please feel free to comment below or contact me.