在GridLayout中为所有适配器项重复相同的数据

时间:2016-03-16 06:51:13

标签: android grid-layout android-gridlayout

在网格布局中,我填充了46个数据(名称和图像),但只有前6个数据一次又一次地重复。

 public View getView(int position, View convertView, ViewGroup parent) {
      // TODO Auto-generated method stub
      View grid;
      LayoutInflater inflater = (LayoutInflater) mContext
          .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      if (convertView == null) {

          grid = new View(mContext);
          grid = inflater.inflate(R.layout.grid_item, null);
          TextView textView = (TextView) grid.findViewById(R.id.txtTitle);
          ImageView imageView = (ImageView)grid.findViewById(R.id.imgGrid);
          textView.setText(web[position]);
          imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
         // imageView.setBackgroundResource(web[position]);
          Glide.with(mContext).load(Imageid[position]).into(imageView);
      } else {
          grid = (View) convertView;//setBackground(Imageid[position]);
      }

      return grid;
  }

2 个答案:

答案 0 :(得分:0)

使用 ViewHolder 初始化网格单元格,如下所示

 public class Viewholder {
        TextView textView;
        ImageView imageView
    }

并更改您的 getView()方法

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Viewholder holder;
    if (convertView == null) {

        holder = new Viewholder();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.grid_list_item, null);

       holder.textView = (TextView) convertView.findViewById(R.id.txtTitle);
     holder.imageView = (ImageView)convertView.findViewById(R.id.imgGrid);


        convertView.setTag(holder);

    } else {

        holder = (Viewholder) convertView.getTag();
    }

    holder.textView.setText(web[position]);
      holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
           Glide.with(mContext).load(Imageid[position]).into(holder.imageView);

    return convertView;
}

答案 1 :(得分:0)

这是因为滚动时它会被循环使用。

做这样的事

public View getView(int position, View convertView, ViewGroup parent) {
  Holder holder;
  LayoutInflater inflater = (LayoutInflater) mContext
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

  if (convertView == null) {

      holder = new Holder();
      convertView = inflater.inflate(R.layout.grid_item, null);
      holder.textView = (TextView) convertView.findViewById(R.id.txtTitle);
      holder.imageView = (ImageView)convertView.findViewById(R.id.imgGrid);
      convertView.setTag(holder);

  } else {
      holder = (Holder) convertView.getTag();
  }
  holder.textView.setText(web[position]);
  holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
  Glide.with(mContext).load(Imageid[position]).into(holder.imageView);
  return grid;
}
class Holder{
   TextView textView;
   ImageView imageView;
}

我希望这会有所帮助。