我希望在我的应用中将图片列表设为GridView
。我正在使用ImageAdapter
课程来初始化GridView
。
这是我的ImageAdapter
课程:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Constructor
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) {
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;
}
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7
};
}
但我想使用ArrayList<Bitmap>
代替Integer[] mThumbIds
。
我的Bitmap
arraylist是这样的:
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
byte[] data = null;
for (int i = 0; i<image.size(); i++) {
try {
data = Base64.decodeBase64(image.get(i).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
bitmaps.add(BitmapFactory.decodeByteArray(data, 0, data.length));
}
我该怎么做?
答案 0 :(得分:3)
您只需使用ImageView
中的setImageBitmap()
方法即可。
在您的特定情况下,在ImageAdapter
类上,在构造函数上传递Bitmap
数组。
private ArrayList<BitMap> images;
// Constructor
public ImageAdapter(Context c, ArrayList<BitMap> images) {
mContext = c;
this.images = images;
}
然后,在getView()
方法上,将图像设置为:
imageView.setImageBitmap(images.get(position);
你可以安全地删除它:
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7
};
答案 1 :(得分:0)
不是将mThumbIds传递给适配器,而是传递位图的arraylist。
如果要解码位图,则需要特别小心,以免在UI线程上完成。 这可以使用AsyncTask完成。请参阅:http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
另外,对于缓存位图,要缓存的位图数量应取决于可用内存。