android listview:如何更改特定单元格的背景颜色(按索引)?

时间:2013-04-25 18:40:37

标签: java android listview

您好,并提前致谢,

有没有办法改变特定细胞的背景颜色?即按索引号码?我试图通过添加--if(position == 3)来修改下面的教程代码。不确定我做错了什么,或者甚至是否允许。非常感谢任何帮助。

public ItemListBaseAdapter(Context context, ArrayList < ItemDetails > results) {
    itemDetailsrrayList = results;
    l_Inflater = LayoutInflater.from(context);
}

public int getCount() {
    return itemDetailsrrayList.size();
}

public Object getItem(int position) {
    return itemDetailsrrayList.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = l_Inflater.inflate(R.layout.item_details_view, null);
        holder = new ViewHolder();
        holder.txt_itemName = (TextView) convertView.findViewById(R.id.name);
        holder.txt_itemDescription = (TextView) convertView.findViewById(R.id.itemDescription);
        //  holder.txt_itemPrice = (TextView) convertView.findViewById(R.id.price);
        holder.itemImage = (ImageView) convertView.findViewById(R.id.photo);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    ////////////////////////////  TEST CODE - Header cells ////////////////


      if(position == 2){
      convertView.setBackgroundColor(android.R.color.background_light);
  }

    if (position == 3) {
         convertView.setBackgroundColor(android.R.color.background_light);
    }
    if (position == 14) {
         convertView.setBackgroundColor(android.R.color.background_light);
    }
    /////////////////////////////////////


    holder.txt_itemName.setText(itemDetailsrrayList.get(position).getName());
    holder.txt_itemDescription.setText(itemDetailsrrayList.get(position).getItemDescription());
    // holder.txt_itemPrice.setText(itemDetailsrrayList.get(position).getPrice());
    holder.itemImage.setImageResource(imgid[itemDetailsrrayList.get(position).getImageNumber() - 1]);

    return convertView;
}

2 个答案:

答案 0 :(得分:1)

据我所知,BaseAdapater中没有setBackground()(如果这是你继承的那个)。如果setBackground()是您创建的方法,我不明白如果您不将其作为参数传递,您将如何设置特定视图的颜色。你不想调用convertView。setBackgroundColor()吗?

答案 1 :(得分:0)

对于任何其他初学者,将此片段添加到getView()对我有用。希望它可以帮到某人。

 if(position == 0 || position == 7 || position == 9 || position == 15 ){


      convertView.setBackgroundColor(Color.DKGRAY);
  }
  else
  {
      convertView.setBackgroundColor(Color.BLACK);
  }