我使用的GalleryView有大约40张图片,而且速度很慢,因为没有回收...
任何人都可以向我展示一个基本的回收GalleryView on getView的方法。
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageIds = {
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
};
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = c.obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = a.getResourceId(
R.styleable.HelloGallery_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}发布于 2011-10-18 02:11:21
您应该将convertView转换为所需的视图,而不是在getView中创建新的ImageView。下面是一个这样做的例子:
public View getView(int position, View cv, ViewGroup parent) {
if (! convertView istanceof ImageView)
{
ImageView cv = new ImageView(mContext);
cv.setLayoutParams(new Gallery.LayoutParams(150, 100));
cv.setScaleType(ImageView.ScaleType.FIT_XY);
cv.setBackgroundResource(mGalleryItemBackground);
}
cv.setImageResource(mImageIds[position]);
return cv;
}只需转换convertView以匹配您想要的内容,但首先要确保它是正确的视图类型。
更新:在显示图像之前,您还应该对图像进行下采样。假设您有一个500x500像素的图像保存在res/drawable下,但该图像在屏幕上只占125x125像素。在显示图像之前,您需要对图像进行下采样。要知道需要对位图进行多少下采样,必须首先获得它的大小
int maxSize = 125; // make 125 the upper limit on the bitmap size
int resId; // points to bitmap in res/drawable
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true; // Only get the bitmap size, not the bitmap itself
BitmapFactory.decodeResource(c.getResources(), resId, opts);
int w = opts.outHeight, h = opts.outHeight;
int maxDim = (w>h)?w:h; // Get the bigger dimension现在我们有了大小,计算图像下采样的量。如果我们有一个500x500的位图,我们想要一个125x125的位图,我们从int inSample = 500/125;得到的每4个像素中就有1个
int inSample = maxDim/maxSize;
opts = new BitmapFactory.Options();
opts.inSampleSize = inSample;现在,只需对资源进行解码,我们就有了下采样的位图。
Bitmap b = BitmapFactory.decodeResource(c.getResources(), resId, opts);请记住,原始位图不受影响。您可以再次对图像进行解码,并将opts.inSampleSize设置为1,您将获得整个500x500位图图像。
发布于 2011-10-18 03:33:26
Gallery小部件实际上有一个bug,导致它总是返回一个空的convertView。这意味着,即使您实现了一个使用convertView的getView方法,您也不会获得性能,因为它无论如何都会创建一个新方法。
一种可能的解决方案。这个人基本上接受了Gallery小部件,并对其进行了必要的更正。您可以下载EcoGallery并将其包含在您自己的包中,这样您就可以使用可以正确回收的Gallery Widget。你的其他选择是:(1)实现你自己的逻辑来保存和使用View对象的缓存。(2)找到一些其他的View Widget组合,以达到与gallery相似的效果,并使用它们来代替实际的Gallery Widget。
请注意,如果您选择下载此EcoGallery,您需要站点上列出的3个java文件,并且您必须从您的sdk中抓取2个不同的xml文件,并将它们包含在您的项目中。
https://stackoverflow.com/questions/7797641
复制相似问题