Search code examples
androidandroid-listviewlistviewitemlistview-adapter

Changing listviewitem background color in adapter gives unexpected results


I am populating a ListView from an ArrayList and in the getView() method of the adapter I am trying to set the background color of a specific item based on a property of the User that it is displaying.

The code I pasted below gives me unexpected results on scrolling the list view. When I enter the application the first items displayed are colored properly, but as I scroll the list it colors some items green, despite the fact that the tested property is 0.

public View getView(int position, View convertView, ViewGroup parent) {

  User user = getItem(position);

  if (convertView == null) {
    convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false);
  }

  if (user.newStatus > 0) convertView.setBackgroundColor(Color.GREEN);

  //some other stuff happens here

  return convertView;
}

In case I didn't explain well, even though user.newStatus is 0, SOME ListViewItems get colored green regardless.


Solution

  • This happens because of ListView's recycling mechanism.

    Adding the else case, will fix it:

    if (user.newStatus > 0) {
       convertView.setBackgroundColor(Color.GREEN);
    } else {
       convertView.setBackgroundColor(yourDefaultColor);
    }