Android ListView row color

后端 未结 2 823
北海茫月
北海茫月 2021-01-26 09:48

I\'m trying to change the row color of my listView in customAdapter. There\'s an array of integer that include 0 and 1, I\'m trying to read from the array and change the color o

相关标签:
2条回答
  • 2021-01-26 10:14

    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.

    0 讨论(0)
  • 2021-01-26 10:25

    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); 
      }
      ...
    }
    
    0 讨论(0)
提交回复
热议问题