ListView数据显示混乱
在使用自定义ListView视图时,经常会采用重用ListView中视图的方式来提高滑动和显示效率,但是随之而来的一个问题是listview中数据经常显示混乱。
通常情况下,我们重写的方法是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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的时候我们并没有去重新加载数据,写成下面这种形式就会重新加载数据了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @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; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步