0

我正在从 ArrayList 填充 ListView,并且在适配器的 getView() 方法中,我试图根据它正在显示的用户属性设置特定项目的背景颜色。

我在下面粘贴的代码在滚动列表视图时给了我意想不到的结果。当我进入应用程序时,显示的第一个项目被正确着色,但是当我滚动列表时,它会将一些项目着色为绿色,尽管测试的属性是 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;
}

万一我解释得不好,即使user.newStatus是 0,一些 ListViewItems 无论如何都会变成绿色。

4

1 回答 1

1

这是因为ListView 的回收机制

添加else案例,将修复它:

if (user.newStatus > 0) {
   convertView.setBackgroundColor(Color.GREEN);
} else {
   convertView.setBackgroundColor(yourDefaultColor);
}
于 2016-01-18T19:06:37.357 回答