重写getView方法时,由于把item中的控件定义成全局变量,在接下来的复用缓存中把填充布局文件与找控件的代码写成这样
if(convertView == null){
view = View.inflate(MainActivity.this, R.layout.item_listview, null);
tv_title = (TextView) view.findViewById(R.id.tv_title);
tv_text = (TextView) view.findViewById(R.id.tv_text);
comment = (TextView) view.findViewById(R.id.tv_comment);
iv = (ImageView) view.findViewById(R.id.iv);
}
else{
view = convertView;
}
item中的控件只找一次,结果尽管后面每次都重新设置了控件的内容,在下一页的条目都重复了前面内容。
如果条目的控件比较多,应该用ViewHolder:
首先创建一个ViewHolder的内部内,定义所有成员变量;
然后在没有缓存的时候,每次填充View对象时,创建一个ViewHolder对象,然后用view.setTag()方法把ViewHolder对象一一对应的绑定到每天一个item的view对象中,(ViewHolder对象的个数和缓存的个数一样)这样在下次从缓存中取出View对象时同时把ViewHolder取出,不用重新找控件。
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder myHolder = null;
if(convertView == null){
<span style="white-space:pre"> </span>view = View.inflate(MainActivity.this, R.layout.item_listview, null);
myHolder = new ViewHolder();
myHolder.tv_title = (TextView) view.findViewById(R.id.tv_title);
myHolder.tv_text = (TextView) view.findViewById(R.id.tv_text);
myHolder.comment = (TextView) view.findViewById(R.id.tv_comment);
myHolder.iv = (ImageView) view.findViewById(R.id.iv);
view.setTag(myHolder);
}
else{
view = convertView;
myHolder = (ViewHolder) view.getTag();
}
myHolder.tv_title.setText(newsList.get(position).getTitle());
myHolder.tv_text.setText(newsList.get(position).getText());
myHolder.comment.setText(newsList.get(position).getComment());
setImageFromeUrl(myHolder.iv,newsList.get(position).getUrl());
return view;
}
class ViewHolder{
private TextView tv_title;
private TextView tv_text;
private TextView comment;
private ImageView iv;
}