Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 277
Mark Manickaraj Avatar asked Dec 21 '25 05:12

Mark Manickaraj


1 Answers

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.)

like image 120
Sam Avatar answered Dec 22 '25 19:12

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!