1

I got a long listview, I tried to change the color in a particular cell, e.g position == 0, it works fine. But when I scroll down the list, another cell that out of the screen before is also change. any idea? thanks for the help

public class CheckWinNoAdapter extends ArrayAdapter<String> {
private final Context context;
private String[] values;
TextView tvMain;




public CheckWinNoAdapter(Context context, String[] values) {
    // TODO Auto-generated constructor stub
    super(context, R.layout.list_draw, values);
    this.context = context;
    this.values = values;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        convertView = inflater.inflate(R.layout.list_draw, parent, false);
    }

    tvMain = (TextView) convertView.findViewById(R.id.chk_main);
    tvMain.setText(values[position]);



    if(position ==0){
        tvMain.setTextColor(Color.BLUE);
    }

    return convertView;
Ricky Zheng
  • 1,279
  • 3
  • 16
  • 27
  • also definitely worth watching http://www.google.com/events/io/2010/sessions/world-of-listview-android.html – biegleux Jul 22 '12 at 07:44

2 Answers2

2

You are recycling views by reusing convertView, you have to always set the color in getView(), like

if (position == 0) {
    tvMain.setTextColor(Color.BLUE);
} else {
    // set color back to original color
    tvMain.setTextColor(Color.BLACK);
}

See http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/

biegleux
  • 13,179
  • 11
  • 45
  • 52
  • hi biegleux, thanks for the anwser. just wondering how can i stop the listview for recycling? – Ricky Zheng Jul 22 '12 at 07:44
  • Don't stop it! Your listview will be slow by not reusing the view, if you remove (convertView == null) check and always call convertView = inflater.inflate(), you will inflate new view each time an item in listview is visible, it is quite slow operation and may slow down scrolling, use the approch described above, not recycling view is really a bad practice, see also http://stackoverflow.com/q/3817628/1300995 – biegleux Jul 22 '12 at 07:50
0

Ok, I figure out by myself now, instead of ding if (convertView == null) {} I use

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



    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = inflater.inflate(R.layout.list_draw, parent, false);
        TextView tvMain = (TextView) rowView.findViewById(R.id.chk_main);
return rowView;

so not recycling views, just in the rowView.

Ricky Zheng
  • 1,279
  • 3
  • 16
  • 27