I have been following the ViewHolder pattern for a ListView, below the code. Actually it works well - but I have a problem.
My items in the adapter have the following layout:
================================================================
| Item title |AddIcon|RemoveIcon|EditIcon|
================================================================
The problem is the following: When I click on the RemoveIcon, after the code runs, I want the RemoveIcon to change color. I do this in the second-last line of the code below with setImageResource. Now that also works fine - the icon is changed. But now, when I scroll, at every specific interval (on my phone it's 8 items), the icon ALSO CHANGES. Looks like caching kicks in here?
Questions:
- Can I use this caching when layout is essentially individual for each item?
If I maybe cannot, will it be ok to use a un-cached layout and repeat it for each item? Currently I may have around 100 items in the list. Is there a better way to do this?
public class ItemListAdapter extends ArrayAdapter<StoreItem> { static class ViewHolder { public TextView title; public ImageButton more; public ImageButton less; public ImageButton edit; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View rowView = convertView; // reuse views if (rowView == null) { LayoutInflater inflater = mContext.getLayoutInflater(); rowView = inflater.inflate(R.layout.item_layout, parent, false); ViewHolder viewHolder = new ViewHolder(); viewHolder.title = (TextView) rowView.findViewById(R.id.title); viewHolder.more = (ImageButton) rowView.findViewById(R.id.item_mas); viewHolder.less = (ImageButton) rowView.findViewById(R.id.item_menos); viewHolder.edit = (ImageButton) rowView.findViewById(R.id.item_edit); rowView.setTag(viewHolder); } final ViewHolder holder = (ViewHolder) rowView.getTag(); final StoreItem item = mItems.get(position); holder.title.setText(item.getTitle()); holder.less.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //dialog is a confirmation dialog, initialization omittted for brevity dialog.setConfirmClickListener(new View.OnClickListener() { @Override public void onClick(View v) { removeItem(item, v); holder.less.setImageResource(R.drawable.x_ok); dialog.getDialog().cancel(); } }); } });