user4297729 user4297729 - 27 days ago 8
Android Question

Altering Color of specific ListView Positions issue

Hey so I'm trying to change the color of specific positions in a listview. Im able to change the color of the positions I want but there seems to be a pattern where 10 positions down the list from the item I want to highlight is also highlighted and I can't figure out why.

Heres how my custom adapter.java is set up with the color change code.

package com.example.zach.listview;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;


class CustomAdapter extends ArrayAdapter<String>{
public CustomAdapter(Context context, String[] routes) {
super(context, R.layout.custom_row ,routes);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {

LayoutInflater routeInflater = LayoutInflater.from(getContext());
View customView = convertView;
if(customView == null){customView = routeInflater.inflate(R.layout.custom_row, parent, false);}

String singleRoute = getItem(position);
TextView routeText = (TextView) customView.findViewById(R.id.routeText);

routeText.setText(singleRoute);

//if (getItem(position).equals("Information")){
// routeText.setBackgroundColor(Color.GRAY);
//}

if(position == 0)
{
routeText.setBackgroundColor(Color.GRAY);
}
return customView;
}
}

Answer

THis is because of recycling. The same views are reused as you scroll. If you set a value for a view, you must reset it to default in the else statement, or it will stay set when its recycled.

Basic rule of list views- if you ever set something, always set it.