ListView数据显示混乱
在使用自定义ListView视图时,经常会采用重用ListView中视图的方式来提高滑动和显示效率,但是随之而来的一个问题是listview中数据经常显示混乱。
通常情况下,我们重写的方法是这样的:
inflater = LayoutInflater.from(context);
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.book_item, null);
holder = new ViewHolder(convertView);
Book book = books.get(position);
holder.bookName.setText(book.getName());
holder.bookTime.setText(book.getTime());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
class ViewHolder {
ImageView bookPic;
TextView bookName;
TextView bookTime;
public ViewHolder(View view) {
bookPic = (ImageView) view.findViewById(R.id.iv_book_pic);
bookName = (TextView) view.findViewById(R.id.tv_book_name);
bookTime = (TextView) view.findViewById(R.id.tv_book_time);
}
}
这样通常会造成list显示混乱,是因为当我们重用视图但是convertView != null的时候我们并没有去重新加载数据,写成下面这种形式就会重新加载数据了:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.book_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Book book = books.get(position);//不管视图是否重用,都重新设置数据
holder.bookName.setText(book.getName());
holder.bookTime.setText(book.getTime());
return convertView;
}