如何在网格视图中设置位图

时间:2014-02-07 08:53:15

标签: android gridview bitmap

我的代码中有nullPointerException这是adapter

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private Bitmap btimaprecieve;

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return mThumbIds.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    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;
    }

    private Integer[] mThumbIds = { R.drawable.sample_pic,
            R.drawable.sample_pic, R.drawable.sample_pict,
            R.drawable.sample_pict, R.drawable.sample_pic, };

    public Bitmap add(Bitmap bitmap_recieve) {
        return btimaprecieve;
    }
}

这是我提到gridview的主要活动

       myImageAdapter= new ImageAdapter(this);
       gridview.setAdapter( myImageAdapter);
      myImageAdapter.add(Bitmap_recieve); 

2 个答案:

答案 0 :(得分:1)

你在

获得了NPE
public Object getItem(int position) {
       return null;  
}

所以,你应该替换这个

public int getCount() {
    return mThumbIds.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

使用

@Override
public int getCount() {
    return mThumbIds.length;
}

@Override
public Object getItem(int position) {
    return mThumbIds[position];
}

@Override
public long getItemId(int position) {
    return position;
}

答案 1 :(得分:0)

检查你的getItem()和getItemId()方法它应该是这样的

@Override
public Object getItem(int position) {
    return mThumbIds.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}