Android ListView row color

邮差的信 提交于 2019-12-02 07:49:05

Fast solution (not very nice code, but works):

@Override
public int getItem(int position){
  return test.get(position);
}


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

  int color0 = ....
  int color1 = ....
  int colorDefault = ...

  switch (test.get(position)) {
     case 0:
             convretview.setBackgroundColor(color0);
             break;
     case 1:
            convretview.setBackgroundColor(color1);
            break;
     default:
           convretview.setBackgroundColor(colorDefault); 
  }
  ...
}

getView() is called for each row in a list so you should not loop over all items in test but only handle the one denoted by position and you should do that after (not in) the if (convertView == null) block.

Edit:

getView() should do the following things:

  • Check if convertView isn't null (if it is, create a new View as you did)
  • Check if convertView is of the right type (this only matters if more than one kind of View is used in the list which is not the case here). If the type is wrong, create a new View.

Now we have a valid View for the list row.

  • Retrieve the data which affects how to display this row. In your case this would be the result of test.get(position). The position is the number of the requested row (starting with 0 at the top of the ListView).
  • Adjust the View according to your data (you did this in the for-loop but you should do it only once for the requested entry at position).
  • Return the View

In more complex situations you may have to do the third step before the second but not here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!