BaseAdapter中getView方法如何编写正确?
老师的代码 写法如下:
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView == null){ viewHolder = new ViewHolder(); convertView = mInflater.inflate(R.layout.item_layout,null); viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon); /***************************(老师版本)这三行代码放这里 Start********************************/ String url = mList.get(position).newsIconUrl; viewHolder.ivIcon.setTag(url); mImageLoader.showImageByAsyncTask(viewHolder.ivIcon, url); /*************************(老师版本)这三行代码放这里 End***********************************/ viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title); viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_content); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.ivIcon.setImageResource(R.mipmap.ic_launcher); viewHolder.tvTitle.setText(mList.get(position).newsTitle); viewHolder.tvContent.setText(mList.get(position).newsContent); return convertView; }
按照老师的写法程序在滚动时奔溃,我Debug找到的崩溃地点是: ImageLoader类中的loadImages函数中的:
// 通过URl找到imageView
ImageView imageView = (ImageView) mListView.findViewWithTag(url); //此处崩溃!!! 提示findViewWithTag无法找到ImageView!
imageView.setImageBitmap(bitmap);
修改成下面的方式(移动3行代码):
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView == null){ viewHolder = new ViewHolder(); convertView = mInflater.inflate(R.layout.item_layout,null); viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon); viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title); viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_content); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.ivIcon.setImageResource(R.mipmap.ic_launcher); /***************************(修改版本)这三行代码放这里 Start******************************/ String url = mList.get(position).newsIconUrl; viewHolder.ivIcon.setTag(url); mImageLoader.showImageByAsyncTask(viewHolder.ivIcon, url); /*************************(修改版本)这三行代码放这里 End********************************/ viewHolder.tvTitle.setText(mList.get(position).newsTitle); viewHolder.tvContent.setText(mList.get(position).newsContent); return convertView; }
修改后没有问题了.
不知道为什么呢?请求解答!