0

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.

HomeIsWhereThePcIs
  • 1,273
  • 1
  • 19
  • 37
  • do if else if (user.newStatus > 0){ convertView.setBackgroundColor(Color.GREEN); }else{ convertView.setBackgroundColor(Color.WHITE); } – Nik Jan 18 '16 at 19:01
  • Oh my god thank you. It was so obvious. I need to take a break :) EDIT: Actually it wasn't that obvious since it is not very logical. Does this have something to do with the views being reused? Since it should be white by default. – HomeIsWhereThePcIs Jan 18 '16 at 19:11
  • @HomeIsWhereThePcIs, try this http://stackoverflow.com/questions/34741895/list-view-item-selected-background-changed-it-changes-other-item-also/34742289#34742289 – Pankaj Nimgade Jan 18 '16 at 19:32

1 Answers1

1

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);
}
Community
  • 1
  • 1
Rami
  • 7,879
  • 12
  • 36
  • 66