更改ListView中第一个项目的背景颜色

3

我有一个用于listview的自定义适配器:

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



    if(row == null)
    {
        LayoutInflater inflater = ((Activity)context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);

        holder = new DataHolder();
        holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
        holder.locationName = (TextView)row.findViewById(R.id.locationName);
        holder.locationElevation = (TextView)row.findViewById(R.id.lcoationElevation);
        holder.locationDistance = (TextView)row.findViewById(R.id.locationDistance);
        row.setTag(holder);
    }
    else
    {
        holder = (DataHolder)row.getTag();
    }

    Data data = gather[position];
    holder.locationName.setText(data.locationName);
    holder.locationElevation.setText(data.locationElevation);
    holder.locationDistance.setText(Double.toString(data.heading));
    holder.imgIcon.setImageBitmap(data.icon);



    return row;
}

我的列表视图已经被项目填充,我只想让第一个项目具有红色背景颜色。当我滚动时,所有其他项目仍然保持自己的颜色,但是第一个项目仍然是红色。有什么建议吗?每次我尝试做些什么时,红色背景颜色都会在我滚动时移动到其他行。
1个回答

10
每次我尝试做些什么时,红色背景会在我滚动时移动到其他行。
我猜你没有else子句。适配器为了节省资源而重用每个行布局。所以如果您更改布局中的值,它将在下一次重新使用此特定布局时保留。只需添加一个else语句将回收的View返回到其默认状态即可:
if(position == 0)
    row.setBackgroundColor(Color.RED);
else
    row.setBackgroundColor(0x00000000); // Transparent

(如果背景是特定的颜色,而不是透明的,则需要更改该值)


噢,@Sam,你是个天才啊。 - chhameed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接