相信大家在使用android的listview或者gridview控件时为了优化,大家会使用自定义的viewHolder或者叫viewCache
如下:
public View getView(int position, View convertView, ViewGroup parent) { ViewCache viewCache; if (convertView == null) { convertView = View.inflate(mContext, R.layout.forum_item, null); viewCache = new ViewCache(convertView); convertView.setTag(viewCache); } else { viewCache = (ViewCache)convertView.getTag(); } TextView title = viewCache.getTitle(); ImageView image = viewCache.getImage(); }
class ViewCache { private View baseView; private TextView title; private ImageView image; public ViewCache(View view) { baseView = view; } public TextView getTitle() { if (title == null) { title = (TextView)baseView.findViewById(R.id.txt_title); } return title; } public ImageView getImage() { if (image== null) { image = (ImageView )baseView.findViewById(R.id.image); } return image ; }}
这样子可以对listview或者gridview进行数据优化,使得他们的使用更加流畅,但是也出现了问题,比如上面的图片有时显示在上面了,下面没有图片,而互动这些控件时使用缓存时会出现如下情况:
本来没有图片的地方也出现图片了,
纳尼??我遇到了···真的遇到了·使用缓存是有好处,但此时··咳咳···你懂吧···
如何解决呢?废话少说:
在网上看到别人写的方法总结的挺好,我亲自试了下,主要是写一个方法
姑且叫做private void resetViewCache(ViewCache viewcache){ viewcache.title.settext(null); viewcache.image.setImageDrawable(null); }
现在重置有了,那么在哪里调用呢?对了,就是在获取缓存view时,在getView()方法里的viewCache = (ViewCache)convertView.getTag();代码下面加上这个方法。修改后的getView()方法为:public View getView(int position, View convertView, ViewGroup parent) { ViewCache viewCache; if (convertView == null) { convertView = View.inflate(mContext, R.layout.forum_item, null); viewCache = new ViewCache(convertView); convertView.setTag(viewCache); } else { viewCache = (ViewCache)convertView.getTag(); resetViewCache(viewCache); } TextView title = viewCache.getTitle(); ImageView image = viewCache.getImage(); }