Nov 19, 2011

Android :: wrong image / data in ListView rows

Android's ListView reuses list items when they aren't need anymore. For this reason, you need to make sure all views that should change, will actually get changed. Your problem is that if you don't find a drawable for the current list item, you don't empty nor hide the ImageView. You should do thumb.setImageDrawable(null) in that case, or thumb.setVisibility(View.GONE).
- From stackoverflow

Example code:


 @Override
     public View getView(int pos, View v, ViewGroup parent) {
      TimetableViewHolder timetableHolder;
         if (v == null) {
             LayoutInflater vi = ((Activity)context).getLayoutInflater();
             v = vi.inflate(R.layout.timetable_item, parent, false);
             timetableHolder = new TimetableViewHolder();
             timetableHolder.rel = (TextView) v.findViewById(R.id.rel);
             timetableHolder.time = (TextView) v.findViewById(R.id.time);
             timetableHolder.icon = (ImageView) v.findViewById(R.id.icon);
             v.setTag(timetableHolder);
         } else {
          timetableHolder = (TimetableViewHolder) v.getTag(); 
         }

         TimetableItem item = items.get(pos);

         if(item != null) {
          timetableHolder.rel.setText(item.rel);
          timetableHolder.time.setText(item.time);
          if(item.url.equals("ERROR")) {
           timetableHolder.icon.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
          } else if(item.url.equals("PRESTOP")) {
           timetableHolder.icon.setImageResource(android.R.drawable.ic_menu_directions);
          } else { // THIS IS IMPORTANT
           timetableHolder.icon.setImageResource(android.R.drawable.ic_dialog_info);
          }
         }

         return v;
     }

1 comment:

Antskr said...

Cheers! Helped me out alot! :)