Skip to content Skip to sidebar Skip to footer

Listview With Favorite Button

In my project I have a listView with star image. If a user touches a star item add to favorite. All code is correct but when listview scroll star image change to unfavorite. This i

Solution 1:

It's a problem of View recycling, basically when you scroll, the View is created again, so the state of your star icon is lost. You would need to implement a logic to check in which state you need to set the icon for every call to getView. A good starting point could be to use the position of the item in the ListView to check, when the View is created, if you need your favorite icon to be set to starred or unstarred. I recommend you read this answer, which explains the mechanism in detail. Here's a simplified example of what you could do :

privateboolean[] favorites; // initialize this array on creation of your adapter with the same size as your listView@Overridepublic View getView(finalint position, View convertView, ViewGroup parent) {
    //the rest of your code if(favorites[position]){
        holder.favicon.setImageResource(R.drawable.favicon);
    else{
        holder.favicon.setImageResource(R.drawable.unfavicon);
    }
    holder.favicon.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {

            if (favorites[position]) {
                holder.favicon.setImageResource(R.drawable.unfavicon);
                favorites[position] = false;
            } else {
                holder.favicon.setImageResource(R.drawable.favicon);
                favorites[position] = true;
            }
        }
    });

I also recommend you start using the ViewHolder pattern for efficiency reasons, although you problem is not related to that.

Solution 2:

Here your problem is favicon object is created again when you scroll ListView. in which tag is not set, as you are setting it programmatically.

My suggestion is use View-Holder pattern.

Solution 3:

First of all, you're inflating a new view each time the getView is called when they should be reused. Check the view holder pattern - Smooth Scrolling

Now about your issue, you either need an array to save the favs state values for each position (an array with the same size as titles) or set the list mode to CHOICE_MODE_MULTIPLE and change the favion state with a backgoung selector.

Post a Comment for "Listview With Favorite Button"