Search code examples
androidandroid-listviewlistviewitem

Not able to set the default background color of some Listview items


I have a Listview, in which I want to set the background of items which were selected earlier. I am trying to achieve this as follows:

public View getView(final int position, View convertView, ViewGroup parent){
------------------
------------------
if(listOfPosts.get(position).isSelected())
        rowView.setBackgroundColor(Color.GRAY);
-----------------
}

But, probably because of view-recycling, background of few other items are also getting changed. How to resolve this issue?


Solution

  • As you guessed, it is indeed caused by view recycling.

    When a view is recycled, its properties are not "reset" or changed back to the defaults - you get it exactly as it is. This means that your code has to ensure that all the view properties are properly set up, even when you just want the "default" (or the value in your layout file).

    In your case, you just have to add an else part to it and set the default background for your row in it:

    if (listOfPosts.get(position).isSelected())
        rowView.setBackgroundColor(Color.GRAY);
    else
        rowView.setBackgroundColor(DEFAULT_COLOR);