gpt4 book ai didi

Android GalleryView 回收

转载 作者:太空狗 更新时间:2023-10-29 15:48:47 29 4
gpt4 key购买 nike

我正在使用 GalleryView 和大约 40 张图片,而且速度很慢,因为没有回收...

任何人都可以向我展示在 getView 方法上对 GalleryView 的基本回收。

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;
}
}

最佳答案

与其在 getView 中创建新的 ImageView,不如将 convertView 转换为您想要的 View 。这是一种方法的示例:

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 以匹配您想要的内容,但首先要确保其 View 类型正确。

更新:您还应该在显示图像之前对图像进行缩减采样。假设您在 res/drawable 下保存了一张 500x500 像素的图像,但该图像在屏幕上只会占用 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 位图图像。

关于Android GalleryView 回收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7797641/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com