Gridview项目没有膨胀?

时间:2016-02-24 05:20:41

标签: android gridview android-arrayadapter

为适配器引用的每个项目创建一个新的ImageView

  public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

这来自developer.google.com 如果它是null,则不会使视图膨胀。但是要在gridview中添加自定义项,我们正在给视图充气......

1 个答案:

答案 0 :(得分:0)

 public class GridAdapter extends BaseAdapter
 {
     private Context context;
     private LayoutInflater layoutInflator;

     private Integer[] mThumbnails 
 =                                                                                                           {R.drawable.kunfu1,R.drawable.kunfu2,R.drawable.kunfu3,R.drawable.kunfu4};

     public GridAdapter(Context c){
      context = c;
      layoutInflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     }


     public View getView(int position, View grid, ViewGroup parent){

         ImageView imageView;
         if(grid == null) {
             grid = layoutInflator.inflate(R.layout.mdv_grid_item, null);
             imageView =  (ImageView)grid.findViewById(R.id.grid_item);

             grid.setTag(imageView);

          }else{
             imageView = (ImageView)grid.getTag();
          }


          imageView.setImageResource(mThumbnails[position]);
          imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

         return grid;

      }

      }