Nithin Np
Nithin Np

Reputation: 190

Android:Listview row background color changing on scroll

This is my code

    public View getDropDownView(int position, View view, ViewGroup parent) {

        ViewHolder holder = null;  

        if(view==null)
        {
            view= inflater.inflate(R.layout.citylist, parent, false);       
            holder=new ViewHolder();
            holder.txtTitle = (TextView) view.findViewById(R.id.tv);    
            holder.txtTitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP,db.getSettings().getInt(15)-3);
            holder.txtTitle.setPadding(10, 10, 10, 10);                     
            view.setTag(holder);        
        }
        else{       
            holder=(ViewHolder)view.getTag();       
        }

        holder.txtTitle.setText(data.get(position));
        if(position % 2 == 0)view.setBackgroundColor(Color.rgb(224, 224, 235));
        return view;
   }

when i scroll the color on even row is also appearing on odd row help

Upvotes: 2

Views: 930

Answers (2)

Neil
Neil

Reputation: 664

Change

if(position % 2 == 0)view.setBackgroundColor(Color.rgb(224, 224, 235));

to

view.setBackgroundColor(position & 1 == 0 ? Color.rgb(224, 224, 235) : android.R.color.transparent);

Upvotes: 1

Tone Ago
Tone Ago

Reputation: 56

The view in the list is recycled. That's the item view scrolled outside to the screed is reused in the item scrolled into the screen. So you need to set the odd item a normal color like this.

if(position % 2 == 0)view.setBackgroundColor(Color.rgb(224, 224, 235));
if(position % 2 == 1)view.setBackgroundColor(The normal color you should set);

Upvotes: 4

Related Questions