简体   繁体   中英

Change Background color of first item in ListView

I have a custom adapter for my 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;
}

My listview is populated with items, I just want the very first item to have a Red background color. As I scroll all the other items remain there own color, but the very first item is still red. Any ideas? Everytime I try something the red background moves around to the other rows as I scroll.

Everytime I try something the red background moves around to the other rows as I scroll.

I'm guessing that you didn't have an else clause. Each row layout is reused by the adapter to save resources. So if you change a value in a layout it will carry over the next time this particular layout is recycled. Simply add an else statement return the recycled View back to it's default state:

if(position == 0)
    row.setBackgroundColor(Color.RED);
else
    row.setBackgroundColor(0x00000000); // Transparent

(If the background was a specific color, instead of transparent, you'll need to change that value.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM