zoukankan      html  css  js  c++  java
  • 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;
      }


  • 相关阅读:
    [BZOJ]2959: 长跑
    http状态码 超详细
    mysql注入常用函数
    tomcat7远程代码执行 ImageMagick 命令执行漏洞
    kali安装redis
    反序列化
    CSP 之dvwa
    token防爆破?
    变量覆盖
    安全狗绕过
  • 原文地址:https://www.cnblogs.com/zhy7104/p/5523919.html
Copyright © 2011-2022 走看看